我收到了一个 node.js 应用程序,用于我负责的生产环境(我是 unix 管理员)。主文件(启动应用程序如下):
var module1 = (require('./module1.js')), ls;
var module2 = (require('./module2.js')), rd;
var module3 = (require('./module3.js')), rs;
var module4 = (require('./module4.js')), rd;
var module5 = (require('./module5.js')), rd;
var module6 = (require('./module6.js')), rd;
var module7 = (require('./module7.js')), rd;
出于好奇(我不是 javascript/node.js 程序员),我尝试在互联网上查找语法。我找到的最接近的是
var module = require('./module.js');
但没有包含括号和 rd/rs/ls 后缀的......
将“require...”放在括号内并添加后缀:rd、rs、ls 的目的是什么?
几点说明: 1. 我问了一位程序员,他告诉我每个模块都会启动一个不同的 Web 应用程序(使用 Express 模块)。 2. 编写这部分的原始程序员不再在公司工作,联系不上,也没有人想接触应用程序的这一部分:-(
最佳答案
理解语法
在 JavaScript 中,当您使用 var
声明变量时,您可以一次声明多个用逗号分隔的变量 (,
)。
例如:
var v1 = "example", v2 = "example2", v3;
v1
, v2
都存在并且有值。 v3
存在,但其值未定义。
在你的案例中应用它
在你的情况下,你有:
var module1 = (require('./module1.js')), ls;
我不知道 require('./module1.js')
返回什么,但为了简单起见,假设它包含 module.exports = "abc"
,这意味着 require('./module1.js')
将返回 "abc"
。
这意味着这一行本质上是:
var module1 = "abc", ls;
module1
的值为 "abc"
,ls
的值为 undefined
。
现在您有一个重复的后缀这一事实确实很奇怪并且似乎没有任何实际用途。它绝对不遵循包含模块的典型模式。它们只是简单的变量,其值为 undefined
(根据提供的代码中显示的内容)。也许它们在代码库的其他地方使用。
编辑
I asked one of the programmers and he told me that each module launches a different web application (using Express module)
默认情况下,在 NodeJS 中,每个模块都有一个 module.exports
对象,它只是一个空对象 {}
。如果在那些需要的模块中,它没有重新分配或添加到 module.exports
,那么 require 将只返回一个空对象。
然而,模块仍然被执行,所以模式(有些人可能称之为反模式)是副作用模块。所需模块除了产生副作用外不提供 API 或其他目的,在本例中启动 Express 应用程序,并可能将监听连接绑定(bind)到不同的端口。
作者本可以这样写
require('./module1.js');
require('./module2.js');
达到同样的效果。当然,如果没有 var
关键字,他们就无法在同时,这可能是作者以他的方式写作的原因。鉴于提供的代码,这些变量的重要性或目的仍然不清楚。
关于javascript - 关于 node.js 应用程序启动的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54843856/