简体   繁体   English

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

[英]How do I make node.js execute some code only if my file is the running file?

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? 这有成语吗?

Check 校验

module.parent

If it's null or undefined , you're the main file. 如果它为nullundefined ,则您是主文件。 If not, you've been require d. 如果没有,你一直require d。 Your module.parent is the module object of the module that require d you. 你的module.parentrequire你的模块的module对象。

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

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