我正在用Node写一个web应用程序。如果我有一些带有init函数的JS文件,我怎么从命令行调用这个函数呢?
当前回答
灵感来自https://github.com/DVLP/run-func/blob/master/index.js
我创建了https://github.com/JiangWeixian/esrua
如果文件index.ts
export const welcome = (msg: string) => {
console.log(`hello ${msg}`)
}
你就跑
esrua ./index.ts welcome -p world
将输出hello world
其他回答
根据其他答案,将以下内容添加到someFile.js
module.exports.someFunction = function () {
console.log('hi');
};
然后可以将以下内容添加到package.json
"scripts": {
"myScript": "node -e 'require(\"./someFile\").someFunction()'"
}
然后,您可以从终端进行呼叫
npm run myScript
我发现这是一种更容易记住和使用命令的方法
如果你的文件只包含你的函数,例如:
myFile.js:
function myMethod(someVariable) {
console.log(someVariable)
}
像这样从命令行调用它什么也不会发生:
node myFile.js
但是如果你改变你的文件:
myFile.js:
myMethod("Hello World");
function myMethod(someVariable) {
console.log(someVariable)
}
现在这将从命令行工作:
node myFile.js
简单的方法:
假设你在项目结构的helpers目录下有一个db.js文件。
现在进入助手目录,进入节点控制台
helpers $ node
2)需要db.js文件
> var db = require("./db")
3)调用你的函数(在你的情况下是init())
> db.init()
希望这能有所帮助
更新2020 - CLI
正如@mix3d指出的那样,你可以只运行一个命令,其中file.js是你的文件,someFunction是你的函数,后面有空格分隔的参数
npx run-func file.js someFunction "just some parameter"
就是这样。
在上面的例子中调用File.js
const someFunction = (param) => console.log('Welcome, your param is', param)
// exporting is crucial
module.exports = { someFunction }
更详细的描述
从CLI直接运行(全局)
安装
npm i -g run-func
使用方法,即运行函数“init”,它必须导出,见底部
run-func db.js init
or
从包运行。Json脚本(本地)
安装
npm i -S run-func
设置
"scripts": {
"init": "run-func db.js init"
}
使用
npm run init
参数个数
以下参数将作为函数参数传入init(param1, param2)
run-func db.js init param1 param2
重要的
函数(在本例中是init)必须在包含它的文件中导出
module.exports = { init };
或ES6导出
export { init };
灵感来自https://github.com/DVLP/run-func/blob/master/index.js
我创建了https://github.com/JiangWeixian/esrua
如果文件index.ts
export const welcome = (msg: string) => {
console.log(`hello ${msg}`)
}
你就跑
esrua ./index.ts welcome -p world
将输出hello world
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在JavaScript中根据键值查找和删除数组中的对象
- 如何合并2 JSON对象从2个文件使用jq?
- 使嵌套JavaScript对象平放/不平放的最快方法
- 在Ubuntu上安装Node.js
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 使用express.js代理
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()