Javascript 从命令行(Node JS)在脚本中运行函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30782693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run function in script from command line (Node JS)
提问by winhowes
I'm writing a web app in Node. If I've got some JS file db.jswith a function initin it how could I call that function from the command line?
我正在用 Node.js 编写一个 Web 应用程序。如果我有一些db.js带有函数的JS 文件,init我如何从命令行调用该函数?
回答by LeeGee
No comment on why you want to do this, or what might be a more standard practice: here is a solution to your question.... Keep in mind that the type of quotes required by your command line may vary.
没有评论您为什么要这样做,或者什么可能是更标准的做法:这是您问题的解决方案......请记住,您的命令行所需的引号类型可能会有所不同。
In your db.js, export the initfunction. There are many ways, but for example:
在您的 中db.js,导出init函数。有很多方法,但例如:
module.exports.init = function () {
console.log('hi');
};
Then call it like this, assuming your db.jsis in the same directory as your command prompt:
然后像这样调用它,假设您db.js与命令提示符位于同一目录中:
node -e 'require("./db").init()'
To other readers, the OP's initfunction could have been called anything, it is not important, it is just the specific name used in the question.
对于其他读者来说,OP 的 init函数可以被称为任何东西,这并不重要,它只是问题中使用的特定名称。
回答by Gaz_Edge
As per the other answers, add the following to someFile.js
根据其他答案,将以下内容添加到 someFile.js
module.exports.someFunction = function () {
console.log('hi');
};
You can then add the following to package.json
然后,您可以将以下内容添加到 package.json
"scripts": {
"myScript": "node -e 'require(\"./someFile\").someFunction()'"
}
From the terminal, you can then call
从终端,您可以拨打
npm run myScript
I find this a much easier way to remember the commands and use them
我发现这是一种更容易记住命令并使用它们的方法
回答by eye_mew
Try make-runnable.
In db.js, add require('make-runnable');to the end.
在 db.js 中,添加require('make-runnable');到最后。
Now you can do:
现在你可以这样做:
node db.js init
Any further args would get passed to the initmethod.
任何进一步的参数都将传递给该init方法。
回答by Pawel
Run directly from CLI (global)
直接从 CLI 运行(全局)
Install
安装
npm i -g run-func
Usage i.e. run function "init", it must be exported, see the bottom
用法即运行函数“init”,必须导出,见底
run-func db.js init
or
或者
Run from package.json script (local)
从 package.json 脚本运行(本地)
Install
安装
npm i -S run-func
Setup
设置
"scripts": {
"init": "run-func db.js init"
}
Usage
用法
npm run init
Params
参数
Any following arguments will be passed as function parameters init(param1, param2)
任何以下参数都将作为函数参数传递 init(param1, param2)
run-func db.js init param1 param2
Important
重要的
the function (in this example init) must be exported in the file containing it
函数(在本例中init)必须导出到包含它的文件中
module.exports = { init };
or ES6 export
或 ES6 导出
export { init };
回答by Siyaram Malav
simple way:
简单的方法:
let's say you have db.js file in a helpers directory in project structure.
假设您在项目结构的 helpers 目录中有 db.js 文件。
now go inside helpers directory and go to node console
现在进入 helpers 目录并转到节点控制台
helpers $ node
2) require db.js file
2) 需要 db.js 文件
> var db = require("./db")
3) call your function (in your case its init())
3)调用你的函数(在你的情况下它的init())
> db.init()
hope this helps
希望这可以帮助
回答by Dave
If you turn db.jsinto a module you can require it from db_init.jsand just: node db_init.js.
如果你变成db.js了一个模块,你可以从以下地方要求它db_init.js:node db_init.js。
db.js:
数据库.js:
module.exports = {
method1: function () { ... },
method2: function () { ... }
}
db_init.js:
db_init.js:
var db = require('./db');
db.method1();
db.method2();
回答by To Kra
This one is dirty but works :)
这个很脏但有效 :)
I will be calling main()function from my script. Previously I just put calls to main at the end of script. However I did add some other functions and exported them from script (to use functions in some other parts of code) - but I dont want to execute main() function every time I import other functions in other scripts.
我main()将从我的脚本中调用函数。以前我只是在脚本的末尾调用 main 。但是我确实添加了一些其他函数并将它们从脚本中导出(以在代码的其他一些部分使用函数) - 但我不想每次在其他脚本中导入其他函数时都执行 main() 函数。
So I did this, in my script i removed call to main(), and instead at the end of script I put this check:
所以我这样做了,在我的脚本中,我删除了对 main() 的调用,而是在脚本的末尾进行了此检查:
if (process.argv.includes('main')) {
main();
}
So when I want to call that function in CLI: node src/myScript.js main
因此,当我想在 CLI 中调用该函数时: node src/myScript.js main
回答by Natan Deitch
I do a IIFE, something like that:
我做了一个 IIFE,就像这样:
(() => init())();
this code will be executed immediately and invoke the init function.
此代码将立即执行并调用 init 函数。
回答by Matt K
Sometimes you want to run a function via CLI, sometimes you want to requireit from another module. Here's how to do both.
有时您想通过 CLI 运行一个函数,有时您想require从另一个模块运行它。这是两者的方法。
// file to run
const runMe = () => {}
if (require.main === module) {
runMe()
}
module.exports = runMe
回答by Elton da Nobrega Mascena
Simple, in the javascript file testfile.js:
很简单,在 javascript 文件 testfile.js 中:
module.exports.test = function () {
console.log('hi');
};
this.test();
Running at the prompt:
在提示符下运行:
node testfile.js

