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 ?
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With