简体   繁体   English

Node JS中的Require模块

[英]Require module in Node JS

I used Node JS for web application development. 我使用Node JS进行Web应用程序开发。 I have a confusion in require() module. 我对require()模块感到困惑。 I am requiring a JS file located in file_handler directory. 我需要位于file_handler目录中的JS文件。 What is the difference between both of the following? 以下两者之间有什么区别?

// in server.js //在server.js中

var chat = require("./file_handler/chat.js");    // Does not work

OR 要么

var chat = require("./file_handler/chat.js")(); // It works

Why is the extra parenthesis in the last of the statement? 为什么在语句的最后加上多余的括号?

In the first line the exported function is assigned to chat variable so then you can call it like next like chat(); 在第一行中,已导出的函数被分配给chat变量,因此您可以像chat();一样调用它chat();

In the second one the return of exported function is returned to chat variable. 在第二个中,导出函数的返回返回到chat变量。

It is actually based on what you export in your module. 它实际上是基于您在模块中export的内容。 If you export the object you need, you can just directly do require('module') . 如果导出所需的对象,则可以直接执行require('module') If you export a function which returns the object you need, you have to execute that exported function require('module')() to get the desired object. 如果导出的函数返回所需的对象,则必须执行该导出的函数require('module')()才能获得所需的对象。

Read the documentation https://nodejs.org/api/modules.html 阅读文档https://nodejs.org/api/modules.html

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

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