簡體   English   中英

Node.js:如何使模塊可用於多個文件?

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

在我編寫的Ruby程序中,我“需要”在“入口點”文件頂部所需的所有文件和模塊。 例如:

#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')在將使用該模塊的所有文件上編寫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');

此示例摘自本文

假設您要使核心模塊“ 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/');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM