如何使node.js仅当我的文件是正在运行的文件时才执行某些代码

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

本文关键字:文件 运行 执行 代码 js node 何使 我的      更新时间:2023-09-26

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

$ node app.js

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

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

我基本上正在寻找这个 ruby 片段的等价物,但在 node.js 中。

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

这有成语吗?

检查

module.parent

如果是nullundefined,您是主文件。如果没有,你已经被require了。您的module.parentrequire您的模块的module对象。