Node.js: 如何使模块对多个文件可用?

Node.js: How to make modules available to multiple files?

在我编写的 Ruby 程序中,我 'required' 我在 'entry point' 文件顶部需要的所有文件和模块。例如:

#Sets an absolute path for wherever the program is run from
#this_file = __FILE__
#BASEDIR = File.expand_path(File.join(this_file, '..'))
this_file = __FILE__
this_file_folder_nav = File.join(this_file, '..')
BASEDIR = File.expand_path(this_file_folder_nav)


#Required Gems
require 'ap'
require 'docx'
require 'sanitize'
etc

#Required files
require_relative "lib/commodity/stories.rb"
require_relative 'lib/worldgrowth/worldgrowth.rb'
require_relative "lib/prices/prices.rb"
require_relative 'lib/prices/prices_module.rb'
etc

I can access all the classes defined in the files above. And I can access classes defined in the 'stories.rb' in pirces_module.rb. All the required gems are accessible in all the files

问题:这是好的做法吗?这对我来说似乎很方便,我想在 node.js.

中做同样的事情

但是,我发现我必须在将使用该模块的所有文件上写 var module = require('someModule')。如果我有一个 node.js 应用程序的入口点文件,是否可以做类似于我在 Ruby 中所做的事情?

您可以创建一个需要所有其他模块的模块,然后在需要的任何地方都需要它。类似于:

var Common = {
  util: require('util'),
  fs:   require('fs'),
  path: require('path')
};

module.exports = Common;

// in other modules
var Common = require('./common.js');

这个例子来自this article

假设您想让核心模块 'http' 可用于您的其他文件。在您的入口点文件中,您可以要求('http')并将该对象附加到 global 对象。此外,您的入口点文件将需要您可能拥有的其他文件。像这样:

var http = require('http')
global.http = http;

var other = require('./other')

现在,其他文件可以访问 http 模块,您可以执行以下操作:

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, "127.0.0.1");

console.log('Server running at http://127.0.0.1:1337/');