use*_*226 2 javascript node.js
我经常看到的默认方法是:
// repeat this in all files
var express = require('express');
var mongoose = require('mongoose');
var async = require('async');
...
Run Code Online (Sandbox Code Playgroud)
但在我的NodeJS应用程序中,我这样做:
// include this only on the server file
_express = require('express');
_mongoose = require('mongoose');
_async = require('async');
...
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用_前缀来识别libs/modules而我不使用,var因为我不想在我的应用程序的每个文件上重复所有包的require/setup.
这样我require()只能在server.js文件上使用一次模块并在任何地方使用它.
这是一个坏主意吗?
模块缓存在nodejs中.最佳做法是在需要时提出要求.
来自node.js文档:
模块在第一次加载后进行缓存.这意味着(除其他外)每次调用require('foo')将获得完全相同的返回对象,如果它将解析为同一个文件.
多次调用require('foo')可能不会导致模块代码多次执行.这是一个重要的特征.有了它,就可以返回"部分完成"的对象,从而允许加载传递依赖,即使它们会导致循环.
http://nodejs.org/api/modules.html
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |