Nodejs,需要模块从一个函数内,或在脚本的顶部。 哪个更适合自定义模块?

我正在写一个自定义脚本,其中包含我所有常用的设置和function。 其中一个函数需要一个时间戳,并使用Moment返回一个自定义格式的人类可读date。

我的自定义脚本位于node_modules文件夹settings.js ,例如文件名为settings.js 。 现在,我知道我可以将其包含在我的任何脚本的顶部

var settings = require('settings.js);

并得到我的function

settings.timestamp_to_date(timestamp,function(date){console.log(date})

我不知道的是包含附加模块(时刻和时刻)的最佳位置。 我现在在函数调用他们,所以他们不加载每个需要settings.js文件的应用程序。 我的想法是,它不会将该模块加载到不需要它的应用程序的内存中。

这让我想到,对于那些可能会使用这个函数的应用程序来说,它会在每次运行函数时都要求模块,这本身就是一个糟糕的select。

哪一个是最好的select,通过将所有的函数放在一个单独的文件中,然后只在某些应用程序需要时才加载所需的函数模块,从而完成我之后的工作?

如果这意味着在每个应用程序中,我必须声明包含settings.js之前要使用的模块,那么这并不理想。 我的应用到目前为止只是为自己学习应用。 我现在创造的东西都不会被很多人使用。

低使用率应用程序的最佳select是什么,在生产环境中可能得到高度利用的应用程序的最佳select是什么?

当search出其他东西时偶然发现这个http://justbuildsomething.com/node-js-best-practices/#2

它列出了几个很好的理由来加载模块在所包含的脚本的顶部与function。

  1. Imagine you had a module that took 30 minutes to load, which is unreasonable, but just imagine. If that module is only needed in one route handler function it might take some time before someone triggers that route and Node.js has to require that module. When this happens the server would effectively be inaccessible for 30 minutes as that module is loaded. If this happens at peak hours several users would be unable to get any access to your server and requests will queue up.
  2. If the module you require causes an error and crashes the server you may not know about the error for several days, especially if you use this module in a rarely used route handler. No one wants a call from a client at 4AM telling them the server is down.

首先,关于是否需要模块内部的模块会导致性能下降,这不是问题。 正如你在Node.js文档中看到的那样,每次你需要一个模块,它都被caching。 任何后续的对该模块的调用将返回与第一次调用相同的引用。

现在,我个人觉得最好把所有的模块声明在文件的顶部,因为它:

  1. 使您更容易知道何时需要一个有bug的模块(例如,崩溃的东西)
  2. 使读者更容易了解模块的所有依赖关系。