从命令行运行脚本中的函数(Node JS) [英] Run function in script from command line (Node JS)

查看:178
本文介绍了从命令行运行脚本中的函数(Node JS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Node中编写一个Web应用程序。如果我有一个JS文件 db.js ,其中有一个函数 init ,我怎么能从中调用该函数命令行?

I'm writing a web app in Node. If I've got some JS file db.js with a function init in it how could I call that function from the command line?

推荐答案

没有评论为什么要这样做,或者可能是更标准的做法:这里是你的问题的解决方案....承担我的命令行所需的报价类型可能会有所不同。

No comment on why you want to do this, or what might be a more standard practice: here is a solution to your question.... Bear in my the type of quotes required by your command line may vary.

db.js 中,导出 init 功能。有很多种方法,但是例如:

In your db.js, export the init function. There are many ways, but for example:

module.exports.init = function () {
  console.log('hi');
};

然后这样调用它,假设你的 db.js 与命令提示符位于同一目录中:

Then call it like this, assuming your db.js is in the same directory as your command prompt:

node -e 'require("./db").init()'

对于其他读者,OP的 init 函数可以被称为任何东西,它并不重要,它只是问题中使用的特定名称。实际上,如果你喜欢这种描述性较低的语法,它本可以避免:

To other readers, the OP's init function could have been called anything, it is not important, it is just the specific name used in the question. Indeed, it could have been avoided if you like this less-descriptive syntax:

node -e 'require("./db").()'

要实现这一点,请使用'特殊'默认引用你的函数, init

To achieve that, have the 'special' default reference your function, init:

module.exports.default = init;

请记住,这是对函数的引用 init ,而不是打电话给它!

Remember that's a reference to the function init, not a call to it!

你也可以使用Node命令行选项来要求模块:

You could also use a Node command line option to require the module:

node --require my-module.mjs -e'foo'

node -r my-module.mjs -e'foo'

...在这种情况下你可以让你的模块添加 foo 到全局命名空间,但离开其他开发人员并不是一件好事,所以我把它留作扭曲的练习。

... in which case you could have your module add foo to the global namespace, but that's not a nice thing to leave other developers with, so I leave that as an exercise for the twisted.

这篇关于从命令行运行脚本中的函数(Node JS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆