通过代码和终端运行节点脚本承诺

时间:2018-05-04 16:55:37

标签: javascript node.js terminal promise

任何人都知道如何运行包含promise作为代码的Node脚本,但同时可以将其用作终端命令?我希望脚本成为链的一部分,但它本身也应该是可执行的。

这应该有用(代码示例):

var myFile = require('foobar')({
  file: 'index.html'
}).then(...);

以及此(终端样本):

$ node ./foobar.js --file=index.html

foobar的内容包含一个承诺,例如:

// foobar.js
module.exports = function(opts) {
    return new Promise(function(resolve, reject) {
        // logic here
        resolve();
    });
};

1 个答案:

答案 0 :(得分:0)

我最终得到了以下解决方案:

/**
 * @param {Object} args
 * @param {String} args.file
 */
module.exports = function(args) {
    return new Promise(function(resolve, reject) {
        //
    });
};

// Check if the second process.argv item is this filename. If so, we 
// know it has been called using `$ node ./foobar.js`
if (process.argv[1] === __filename) {
    // Execute the `module.exports` with the process.argv as an object,
    // converted by `minimist` module.
    module.exports(require('minimist')(process.argv.slice(2)));
}

这样,我可以调用脚本:

require('foobar.js')({file: 'myfile.html'})

但也作为:

$ node ./foobar.js --file=myfile.html

相关问题