在 node.js 应用程序中包含外部. js 文件

我有一个 app.js 节点应用程序。随着这个文件开始增长,我想将代码的一部分移动到 app.js 文件中的其他一些文件中,这些文件是我“需要”或“包含”的。

我在尝试这样的事情:

// Declare application
var app = require('express').createServer();


// Declare usefull stuff for DB purposes
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;


// THE FOLLOWING REQUIRE DOES NOT WORK
require('./models/car.js');

在 car.js:

// Define Car model
CarSchema = new Schema({
brand        : String,
type : String
});
mongoose.model('Car', CarSchema);

我搞错了:

ReferenceError: Schema is not defined

我只是希望加载 car.js 的内容(而不是将所有内容都放在同一个 app.js 文件中) ,在 node.js 中有没有特殊的方法来实现这一点?

132681 次浏览

To place an emphasis on what everyone else has been saying var foo in top level does not create a global variable. If you want a global variable then write global.foo. but we all know globals are evil.

If you are someone who uses globals like that in a node.js project I was on I would refactor them away for as there are just so few use cases for this (There are a few exceptions but this isn't one).

// Declare application
var app = require('express').createServer();


// Declare usefull stuff for DB purposes
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;


require('./models/car.js').make(Schema, mongoose);

in car.js

function make(Schema, mongoose) {
// Define Car model
CarSchema = new Schema({
brand        : String,
type : String
});
mongoose.model('Car', CarSchema);
}


module.exports.make = make;

you can put

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

at the top of your car.js file for it to work, or you can do what Raynos said to do.

The correct answer is usually to use require, but in a few cases it's not possible.

The following code will do the trick, but use it with care:

var fs = require('fs');
var vm = require('vm');
var includeInThisContext = function(path) {
var code = fs.readFileSync(path);
vm.runInThisContext(code, path);
}.bind(this);
includeInThisContext(__dirname+"/models/car.js");

If you just want to test a library from the command line, you could do:

cat somelibrary.js mytestfile.js | node

Short answer:

// lib.js
module.exports.your_function = function () {
// Something...
};


// app.js
require('./lib.js').your_function();

This approach works for me in Node.js, Is there any problem with this one?

File 'include.js':

fs = require('fs');

File 'main.js':

require('./include.js');


fs.readFile('./file.json', function (err, data) {
if (err) {
console.log('ERROR: file.json not found...')
} else {
contents = JSON.parse(data)
};
})