Xinrui Ma Xinrui Ma - 1 year ago 113
Javascript Question

What does require() actually return, the file or the function

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?

Answer Source

The require(...) function returns the module.exports value from the "required" module, and in the case its the Profile function.

As an aside, I have no idea what "return the file" or "the Profile is the profile.js itself" means.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download