Categories
JavaScript Answers

How to include external .js file in Node.js app?

Spread the love

To include external .js file in Node.js app, we create a module.

For instance, we write

const make = (Schema, mongoose) => {
  CarSchema = new Schema({
    brand: String,
    type: String,
  });
  mongoose.model("Car", CarSchema);
};

module.exports.make = make;

in car.js to export the make function.

Then we use it by writing

const app = require("express").createServer();
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

require("./models/car.js").make(Schema, mongoose);

We call require to require the car.js file and call make from the returned object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *