Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 通过代码和终端运行节点脚本_Javascript_Node.js_Terminal_Promise - Fatal编程技术网

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

Javascript 通过代码和终端运行节点脚本,javascript,node.js,terminal,promise,Javascript,Node.js,Terminal,Promise,有人知道如何运行一个节点脚本,其中包含一个作为代码的承诺,但同时使其可用作终端命令吗?我希望脚本是一个链的一部分,但它本身也应该是可执行的 这应该有效(代码示例): 还有这个(终端样本): foobar的内容包含一个承诺,类似于: // foobar.js module.exports = function(opts) { return new Promise(function(resolve, reject) { // logic here resolv

有人知道如何运行一个节点脚本,其中包含一个作为代码的承诺,但同时使其可用作终端命令吗?我希望脚本是一个链的一部分,但它本身也应该是可执行的

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

还有这个(终端样本):

foobar
的内容包含一个承诺,类似于:

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

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

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

// foobar.js
module.exports = function(opts) {
    return new Promise(function(resolve, reject) {
        // logic here
        resolve();
    });
};
/**
 * @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)));
}