For example, I have profile.js
var EventEmitter = require("events").EventEmitter;
var https = require("https");
var http = require("http");
var util = require("util");
function Profile(username) {
// function code here
}
util.inherits( Profile, EventEmitter );
module.exports = Profile;
In my app.js, I have
var Profile = require("./profile.js");
var studentProfile = new Profile("chalkers");
/**
* When the JSON body is fully recieved the
* the "end" event is triggered and the full body
* is given to the handler or callback
**/
studentProfile.on("end", console.dir);
/**
* If a parsing, network or HTTP error occurs an
* error object is passed in to the handler or callback
**/
studentProfile.on("error", console.error);
So the variable is the profile.js itself or the function Profile(username)? What if the profile.js have different functions, say I have function SetProfile(username) in the profile.js, how should I export those two functions and use them in the app.js?
require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object. require() statement not only allows to add built-in core NodeJS modules but also community-based and local modules.
2011-08-26. Node.js follows the CommonJS module system, and the builtin require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object.
The require function is intended to add separate pieces of code (“modules”) to the current scope, a feature that was not part of the JavaScript/ECMAScript language until the ES2015 specification.
With require , you can include them in your JavaScript files and use their functions and variables. However, if you are using require to get local modules, first you need to export them using module.
The require(...)
function returns the module.exports
value from the "required" module, and in the case its the Profile
function.
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