Bra*_*don 5 javascript require node.js
我正在编写一个自定义脚本,其中包含我所有常用的设置和功能。其中一个函数采用时间戳并使用 Moment 返回具有自定义格式的人类可读日期。
我的自定义脚本位于该node_modules
文件夹中,并且该文件被调用settings.js
。现在,我知道我可以使用以下命令将其包含在任何脚本的顶部
var settings = require('settings.js);
并通过以下方式获取我的功能
settings.timestamp_to_date(timestamp,function(date){console.log(date})
我不知道包含附加模块(时刻和时刻时区)的最佳位置。我现在将它们放在函数调用中,这样它们就不会加载到每个需要该settings.js
文件的应用程序上。我的想法是,它不会将该模块加载到不需要它的应用程序的内存中。
不过,这让我想知道,对于可能经常使用此功能的应用程序,每次运行该功能时都需要模块,这本身似乎是一个糟糕的选择。
通过将所有功能放在一个文件中,并仅在特定应用程序需要时加载该功能所需的模块,哪个是完成我所追求的目标的最佳选择?
如果这意味着在每个应用程序中我必须在包含之前声明我要使用哪些模块,settings.js
那么这并不理想。到目前为止,我的应用程序只是为我自己学习应用程序。我目前创建的任何内容都不会被很多人使用。
对于低使用率应用程序来说最好的选择是什么,对于可能在生产环境中高使用率的应用程序来说最好的选择是什么?
在搜索其他内容时偶然发现了这个http://justbuildsomething.com/node-js-best-practices/#2
它列出了在包含的脚本顶部与函数中加载模块的几个充分理由。
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.
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.