简体   繁体   English

Node.js包含JS文件和设置变量

[英]Node.js include JS file and set variables

I'm using Node.js to run background jobs (no frontend). 我正在使用Node.js运行后台作业(无前端)。 I think the best way for me to run the workers is to have one file for each kind of job (like that I can easily run one worker per server). 我认为对我而言,运行这些工作程序的最佳方法是为每种作业都拥有一个文件(例如,我可以轻松地在每个服务器上运行一个工作程序)。

main.js main.js

require('scribe-js')(); // github.com/bluejamesbond/Scribe.js
process.console = console;
...

worker_*.js worker _ *。js

require('./lib/main');

console.tag('testing').log('this is a test');

The console variable isn't passed to worker_*.js. console变量未传递到worker _ *。js。 I to set it in main.js because if the value of the variable ever changes I want to be able to change it only once (in main.js) and not in each worker_*.js file. 我在main.js进行设置,因为如果变量的值发生更改,我希望只能在main.js中进行一次更改,而不能在每个worker _ *。js文件中进行更改。 Any idea? 任何想法?


I think this is not a duplicate : I know there's plenty of "how do I include a JS file in another JS file in Node.js" and the answer is usually "use var s = require('yourfile'); ". 我认为这不是重复的我知道有很多“如何在Node.js中的另一个JS文件中包含一个JS文件”,答案通常是“使用var s = require('yourfile'); ”。 I think this question is a bit different. 我认为这个问题有些不同。

To share a variable between node modules, you can: 要在节点模块之间共享变量,您可以:

  1. Export a method for the module, then call that method and pass it the variable you want to share or 导出模块的方法,然后调用该方法并将您要共享的变量传递给该方法或
  2. You can make the variable global. 您可以将变量设为全局。

The preferred method is to explicitly share a variable via an exported method and then let the module store its own copy of the variable. 首选方法是通过导出的方法显式共享变量,然后让模块存储自己的变量副本。 See here for info about globals. 有关全局变量的信息,请参见此处

In your case, it might make a lot of sense to support a common constructor for each worker and pass the worker an object that you can put properties on to share the same variables to each worker. 在您的情况下,为每个工作程序支持一个通用的构造函数,并为该工作程序传递一个对象,您可以在该对象上放置属性以与每个工作程序共享相同的变量,这可能很有意义。

So, you'd so something like this: 所以,您会这样:

worker_1.js worker_1.js

var savedArgs;
module.exports = function(args) {
    savedArgs = args;
}

And, then when worker_1.js was loaded, you'd do this: 然后,在加载worker_1.js时,您需要执行以下操作:

var args = {console: process.console};
require('./worker_1.js')(args);

The design of modules is to be as self-contained as possible (eg not rely on global state) to encourage modularity and reusability. 模块的设计应尽可能独立(例如,不依赖全局状态),以鼓励模块化和可重用性。 They should require() in what they need and any app configuration or singletons that they need in order to do their job that are created by other modules should be given to them in their constructor or via some other exported method. 他们应该在他们需要的内容中使用require() ,并在其构造函数中或通过其他导出方法将它们所需的任何应用程序配置或单例功能执行给其他模块创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM