From 26cb2aa9a1d5081662e8bc6e117697143508c349 Mon Sep 17 00:00:00 2001 From: oleg Date: Thu, 4 Dec 2014 23:22:14 +0300 Subject: [PATCH] call callback once --- lib/command/spawn.js | 5 +++-- lib/utils.js | 9 +++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/lib/command/spawn.js b/lib/command/spawn.js index a699d64..2e10c95 100644 --- a/lib/command/spawn.js +++ b/lib/command/spawn.js @@ -2,7 +2,8 @@ var spawn = require('child_process').spawn, ParentCommand = require('./base').Command, - inherits = require('util').inherits; + inherits = require('util').inherits, + utils = require('../utils'); function Command(params) { params = params || {}; @@ -22,6 +23,7 @@ Command.prototype.run = function(params, callback) { stdout = ''; if (!params.cmd) return callback(new Error('`cmd` is not set')); if (!params.args) return callback(new Error('`args` is not set')); + callback = utils.once(callback); params.options = params.options || {}; params.options.cwd = params.options.cwd || this.cwd; var cmd = spawn(params.cmd, params.args, params.options); @@ -34,7 +36,6 @@ Command.prototype.run = function(params, callback) { callback(new Error('Spawned command outputs to stderr: ' + data)); cmd.kill(); }); - // TODO; callback should be called only once (port once from underscore) cmd.on('close', function(code) { var err = null; if (code !== 0) err = new Error( diff --git a/lib/utils.js b/lib/utils.js index 4c3fd27..53c72e0 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -13,3 +13,12 @@ exports.isObject = function(obj) { exports.noop = function() {}; exports.slice = Array.prototype.slice; + +exports.once = function(func) { + var isCalled = false; + return function() { + if (isCalled) return; + func.apply(this, arguments); + isCalled = true; + }; +};