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)));
}