Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 833
Luc Avatar asked Apr 11 '11 18:04

Luc


People also ask

How do I include another file in node JS?

To include functions defined in another file in Node. js, we need to import the module. we will use the require keyword at the top of the file. The result of require is then stored in a variable which is used to invoke the functions using the dot notation.

How do I connect an external JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

How do you run a .js file in node JS?

You can Run your JavaScript File from your Terminal only if you have installed NodeJs runtime. If you have Installed it then Simply open the terminal and type “node FileName. js”. If you don't have NodeJs runtime environment then go to NodeJs Runtime Environment Download and Download it.


1 Answers

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; 
like image 133
Raynos Avatar answered Sep 28 '22 03:09

Raynos