如果我的文件是正在运行的文件,我如何使node.js执行一些代码?

时间:2021-01-21 07:07:45

I want to be able to start my express server directly via:

我希望能够通过以下方式直接启动我的快速服务器:

$ node app.js

But I also want to able to require that file, and have it return the app instance but actually not start the server. Then I can start later it with some options.

但我也希望能够要求该文件,让它返回应用程序实例但实际上不启动服务器。然后我可以稍后用一些选项开始。

app = require './app'
app.listen options.someCustomPort

I'm basically looking for the equivalent of this ruby snippet, but in node.js.

我基本上在寻找相当于这个ruby片段的东西,但在node.js中。

if __FILE__ == $0
  app.listen options[:some_custom_port]
end

Is there an idiom for this?

这有成语吗?

1 个解决方案

#1


8  

Check

module.parent

If it's null or undefined, you're the main file. If not, you've been required. Your module.parent is the module object of the module that required you.

如果它为null或未定义,则您是主文件。如果没有,你就被要求了。 module.parent是需要您的模块的模块对象。

#1


8  

Check

module.parent

If it's null or undefined, you're the main file. If not, you've been required. Your module.parent is the module object of the module that required you.

如果它为null或未定义,则您是主文件。如果没有,你就被要求了。 module.parent是需要您的模块的模块对象。