问题描述
我有一个带有导出功能的NodeJS文件,如下所示:
I have a NodeJS file with an export function a bit like this:
test.js
exports.run = function(){
console.log('You run this function!');
};
是否有一种方法可以使用package.json
的scripts
对象中的自定义命令从该文件中专门调用该函数?
Is there a way to specifically call the function from this file using a custom command in the scripts
object of package.json
?
例如,我想它看起来像这样:
For example, I imagine it would look something like this:
{
"author": "Joe Bloggs",
"name": "test-app",
"main": "server.js",
"version": "1.0.0",
"private": true,
"scripts": {
"test": "NODE_ENV=production node test.js run()",
},
"dependencies": {
"express": "~4.10.6",
}
}
很明显,这是运行该函数的语法不正确.
Obviously this is the incorrect syntax to run the function.
推荐答案
您可以使用良好的ol'开关大小写并将参数传递给脚本.
You could use a good ol' switch case and pass arguments to your script.
test.js
function foo(){
console.log('foo is called');
}
function bar(){
console.log('bar is called');
}
for (var i=0; i<process.argv.length;i++) {
switch (process.argv[i]) {
case 'foo':
foo();
break;
case 'bar':
bar();
break;
}
}
module.exports.foo = foo;
module.exports.bar = bar;
package.json
{
"author": "A person",
"name": "test-app",
"main": "server.js",
"version": "1.0.0",
"private": true,
"scripts": {
"test": "NODE_ENV=production node test.js foo bar"
},
"dependencies": {
"express": "~4.10.6"
}
}
test.js:foo()和test.js:bar()现在将由npm test调用.您也可以像往常一样要求它.
这回答了您的问题,但是您以后的评论使我不确定这是否是您要的.
test.js:foo() and test.js:bar() will now be called by npm test. You can also require it like you normally would.
This answers your question, but your later comments made me unsure if this is what you're after.
这篇关于在package.json脚本中调用特定的NodeJS函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!