[javascript] include external .js file in node.js app

I have an app.js node application. As this file is starting to grow, I would like to move some part of the code in some other files that I would "require" or "include" in the app.js file.

I'm trying things like:

// 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');

in car.js:

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

I got the error:

ReferenceError: Schema is not defined

I'm just looking to have the content of car.js loaded (instead of having everything in the same app.js file) Is there a particuliar way to do this in node.js ?

This question is related to javascript node.js

The answer is


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");

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.


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)
    };
})

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();