简体   繁体   English

在package.json脚本中调用特定的NodeJS函数

[英]Call specific NodeJS function in package.json scripts

I have a NodeJS file with an export function a bit like this: 我有一个带有导出功能的NodeJS文件,如下所示:

test.js test.js

exports.run = function(){
  console.log('You run this function!');
};

Is there a way to specifically call the function from this file using a custom command in the scripts object of package.json ? 有没有办法在package.jsonscripts对象中使用自定义命令从此文件中专门调用该函数?

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. 显然这是运行该函数的错误语法。

You could use a good ol' switch case and pass arguments to your script. 你可以使用一个好的'switch case并将参数传递给你的脚本。

test.js 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 的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() and test.js:bar() will now be called by npm test. test.js:foo()和test.js:bar()现在将由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. 这回答了你的问题,但是你后来的评论使我不确定这是否是你所追求的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM