我很无聊,所以我决定尝试回答这个问题,即使我不完全确定这是你要问的。如果您的意思是您只需要从节点 Web 应用程序运行节点脚本并且您通常从终端运行该脚本,只需 require 您的脚本并以编程方式运行它。
让我们假设您运行的这个脚本如下所示:
// myscript.js
var task = process.argv[2];
if (!task) {
console.log('Please provide a task.');
return;
}
switch (task.toLowerCase()) {
case 'task1':
console.log('Performed Task 1');
break;
case 'task2':
console.log('Performed Task 2');
break;
default:
console.log('Unrecognized task.');
break;
}
你通常会这样做:
$ node myscript task1
您可以将脚本修改为如下所示:
// Define our task logic as functions attached to exports.
// This allows our script to be required by other node apps.
exports.task1 = function () {
console.log('Performed Task 1');
};
exports.task2 = function () {
console.log('Performed Task 2');
};
// If process.argv has more than 2 items then we know
// this is running from the terminal and the third item
// is the task we want to run :)
if (process.argv.length > 2) {
var task = process.argv[2];
if (!task) {
console.error('Please provide a task.');
return;
}
// Check the 3rd command line argument. If it matches a
// task name, invoke the related task function.
if (exports.hasOwnProperty(task)) {
exports[task]();
} else {
console.error('Unrecognized task.');
}
}
现在你可以用同样的方式从终端运行它:
$ node myscript task1
或者您可以从应用程序(包括 Web 应用程序)中要求它:
// app.js
var taskScript = require('./myscript.js');
taskScript.task1();
taskScript.task2();
单击动画 gif 以获得更大更流畅的版本。请记住,如果用户通过按钮或其他方式从您的 Web 应用程序调用您的任务脚本,则该脚本将在 Web 服务器上运行,而不是在用户的本地计算机上运行。这应该很明显,但我想我还是会提醒你:)
编辑
我已经做了视频,所以我不打算重做,但我刚刚发现了module.parent。仅当您的脚本是通过 require 从另一个脚本加载时,才会填充 parent 属性。这是测试您的脚本是否直接从终端运行的更好方法。如果您在启动 app.js 文件时传入参数,例如--debug,我这样做的方式可能会出现问题。它会尝试运行一个名为“--debug”的任务,然后打印出“Unrecognized task”。启动应用程序时发送到控制台。
我建议改变这个:
if (process.argv.length > 2) {
到这里:
if (!module.parent) {
参考:Can I know, in node.js, if my script is being run directly or being loaded by another script?