node.js中的require引入问题
伊谢尔伦
伊谢尔伦 2017-04-17 16:10:51
0
2
435

举个例子:在一个项目的主程序server.js中引入mongoose模块,又在另一个文件use.js中给mongoose定义格式和自定义方法,最后在sever.js引入这个文件,可在use.js为什么又要引入mongoose模块,主程序server.js中不是以及经引入了么?
求大佬告知

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(2)
迷茫

In NodeJs, each file is an independent module, and the variables defined inside are in a local scope and cannot be accessed from outside. So, you referenced lib in a.js, probably like this a.js 中引用了 lib,可能是这样

const lib = require("lib");

这里的 lib 是一个局域变量,出了这个文件,其它地方就访问不到了(除非 export)。所以在 b.js 中如果你还需要引用 lib 的话,就得

const lib = requier("lib");

这里的 lib 和之前 a.js 中的 lib rrreee

lib here is a local variable. Once this file is out, it cannot be accessed from other places (unless exported). So if you still need to reference lib in b.js, you have to

rrreee

The lib here and the previous lib in a.js actually point to the same object (both are exported from lib.js), but they (refer to variables ) are in different (independent) scopes. 🎜 🎜If you have written PHP before, you may have difficulty understanding this. PHP's include is equivalent to inserting the included script at the current location, while require in node just introduces the object exported by the corresponding script. If you look at the code of requirejs or seajs, you will understand what node's require is doing. 🎜
洪涛

Each module is independent. To modify mongoose in use, you must require to get the mongoose object, otherwise how can you modify it

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template