NodeJS:最有效的使用方式"要求"

时间:2015-09-01 19:09:33

标签: node.js

使用NodeJS require功能的最佳方法是什么?在此,我指的是require声明的位置。是否最好从脚本的开头加载所有依赖项,因为您需要它们,或者它是否会产生明显的差异?

This article有很多关于require如何运作的有用信息,但我仍然无法得出关于哪种方法最有效的明确结论。

2 个答案:

答案 0 :(得分:2)

Assuming you're using node.js for some sort of server environment, several things are generally true about that server environment:

  1. You want fast response time to any given request.
  2. The code that runs for processing requests should not use synchronous I/O operations because that seriously lessens the scalability of the server.
  3. Server startup time is generally not something you need to optimize for (within reason) so if you're going to pay an initialization cost somewhere, it is usually better paid once at server startup time.

So, given that require() uses synchronous I/O when the module has not yet been cached, that means you really don't generally want to be doing require() operations inside a request handler. And, you want fast response times for your request handlers so you don't want require() calls inside your handler anyway.

All of these leads to a general rule of thumb that you load necessary modules at startup time into a module level variable that you can reuse from one request to the next and you don't load modules inside your request handlers.


In addition to all of this, if you put all your require() statements in a block near the top of your module, it makes your module a lot more self-documenting about what other modules it depends on and how it initializes those modules. If require() statements are sprinkled all over the code, then it makes it a lot harder for a developer to see what this module is using without a lot more study of the code.

答案 1 :(得分:1)

这取决于您正在寻找的性能特征。

require()并不便宜;它必须从磁盘读取JS文件,解析它,并执行任何顶级代码(并通过该文件以递归方式执行所有文件require())。

如果您将所有require()放在最前面,您的代码可能需要更长时间才能启动,但以后不会突然放慢速度。 (请注意,在同步顶级代码中进一步向下移动require()将不会超出执行顺序。

如果第一次异步使用时只有require()个其他模块,则第一个请求可能明显变慢,因为Node会解析所有依赖项。这也意味着来自依赖项的任何错误都不会被捕获,直到以后。 (请注意,所有require()个调用都会被缓存,因此第二个请求将不再执行任何工作)

在整个代码中分散require()调用的另一个缺点是它使其可读性降低;很容易看出每个文件的确切位置。