98

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 ?

2
  • 1
    Schema doesn't exist in that scope. You could try passing Schema into car.js through some sort of exported function, that way you can reference it. That or require mongoose within car.js.
    – Robert
    Apr 11, 2011 at 18:16
  • 3
    Node.js makes use of CommonJS, which divides your code into different modules. The quick rule of thumb, the scope of code in a Node app is the file it is defined in. So you will need to require mongoose in car.js, and in car.js you will need to export whatever the rest of your app needs then require it in your main file like you are doing.
    – Matt Greer
    Apr 11, 2011 at 18:17

6 Answers 6

100

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;
4
  • 32
    Tip for anyone reading, you can just do exports.foo, rather then module.exports.foo Apr 12, 2011 at 2:29
  • 9
    @TylerEgeto I always feel safer if I use the longer version ;)
    – Raynos
    Apr 12, 2011 at 8:15
  • 3
    Would you please expand the example to show how one can use variables defined inside car.js in the main app? e.g. ` function make(...) { ... CarModel = mongoose.model('Car', CarSchema); } ` Inside the app, how does one use CarModel?
    – Marius
    Feb 21, 2012 at 6:10
  • :)) Ok, how about when setting multiple vars inside the function? e.g. multiple models, or even 3 models, and 2 something elses? Should they be returned as part of an object? e.g. return {models: {car: CarModel, dealer: CarDealer}, carStuff: carStuff}
    – Marius
    Feb 21, 2012 at 19:34
57

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

Short answer:

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

// app.js
require('./lib.js').your_function();
2
  • This is not working for me. I am getting error Cannot find module lib.js.
    – Manoj
    Jul 6, 2015 at 7:20
  • 2
    @Manoj you have to prefix lib.js with ./ like so: require('./lib.js').your_function()
    – Chris
    Jul 11, 2015 at 6:19
8

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.

4

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

cat somelibrary.js mytestfile.js | node
0

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)
    };
})
1
  • This is wrong. "fs" is never exported ! Wouldn't work on strict mode which is default in ES6 Jan 30, 2017 at 23:37

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.