【问题标题】:Run Node script promise through code and through terminal通过代码和终端运行 Node 脚本承诺
【发布时间】:2018-05-04 16:55:37
【问题描述】:

有没有人知道如何运行一个包含 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();
    });
};

【问题讨论】:

    标签: javascript node.js terminal promise


    【解决方案1】:

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

    /**
     * @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

    【讨论】:

      猜你喜欢
      • 2012-01-21
      • 2014-08-13
      • 1970-01-01
      • 2019-01-07
      • 2021-05-12
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多