From deee138a8cbc918463d8af5ce8c2bec33c3fd164 Mon Sep 17 00:00:00 2001 From: William Hilton Date: Wed, 11 Dec 2019 12:27:15 -0600 Subject: [PATCH] fix: handle sanitising better, add tests --- index.js | 19 ++++++++++++------- test/test.js | 23 +++++++++++++++++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/index.js b/index.js index 8348b4b..8df6a0f 100755 --- a/index.js +++ b/index.js @@ -5,19 +5,24 @@ var spawn = childProcess.spawn; var exec = childProcess.exec; module.exports = function (pid, signal, callback) { - if (typeof pid !== "number") { - throw new Error("pid must be a number"); + if (typeof signal === 'function' && callback === undefined) { + callback = signal; + signal = undefined; + } + + pid = parseInt(pid); + if (Number.isNaN(pid)) { + if (callback) { + return callback(new Error("pid must be a number")); + } else { + throw new Error("pid must be a number"); + } } var tree = {}; var pidsToProcess = {}; tree[pid] = []; pidsToProcess[pid] = 1; - - if (typeof signal === 'function' && callback === undefined) { - callback = signal; - signal = undefined; - } switch (process.platform) { case 'win32': diff --git a/test/test.js b/test/test.js index 3db1ca1..d988cd7 100644 --- a/test/test.js +++ b/test/test.js @@ -31,4 +31,27 @@ describe('kill()', function(){ return done() }) }) + + it('should reject invalid pid', function(done){ + var p = fork('./test/spin') + assert.ok(p.pid) + + kill('rm -rf /dev/null', function(err) { + assert.ok(typeof err === 'object') + return done() + }) + }) + + it('should reject invalid pids even if no callback', function(done){ + var p = fork('./test/spin') + assert.ok(p.pid) + + try { + kill('rm -rf /dev/null') + assert.fail('should have thrown') + } catch (err) { + assert.ok(typeof err === 'object') + return done(); + } + }) })