[ACCEPTED]-include external .js file in node.js app-node.js

Accepted answer
Score: 100

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

If you are someone who uses globals 5 like that in a node.js project I was on 4 I would refactor them away for as there 3 are just so few use cases for this (There 2 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 1 car.js

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

module.exports.make = make;
Score: 57

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

The following 2 code will do the trick, but use it with 1 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");
Score: 18

Short answer:

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

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

0

Score: 8

you can put

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

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

Score: 4

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

cat somelibrary.js mytestfile.js | node
Score: 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)
    };
})

0

More Related questions