Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 816
Xinrui Ma Avatar asked Oct 26 '16 19:10

Xinrui Ma


People also ask

What does require () do in JavaScript?

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.

What is require () in NodeJS?

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.

What does require do in react js?

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.

Can I use require in js file?

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.


1 Answers

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.
like image 103
Amit Avatar answered Sep 22 '22 08:09

Amit