Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs new require()

Are these two lines the same?

var myModule = new require('my-module')

and:

var myModule = require('my-module')

The former helps intelliJ Idea (or Webstorm) to do autocompletion on methods (e.g "model" in mongoose) (at least it doesn't show the annoying yellow underline that says "Unresolved function or method"

like image 546
arg20 Avatar asked Apr 16 '14 14:04

arg20


People also ask

What is require () in NodeJS?

require() is used to consume modules. It allows you to include modules in your app. You can add built-in core Node. js modules, community-based modules (node_modules), and local modules too.

Why is require () used in NodeJS?

In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

How add NodeJS require?

You can think of the require module as the command and the module module as the organizer of all required modules. Requiring a module in Node isn't that complicated of a concept. const config = require('/path/to/file'); The main object exported by the require module is a function (as used in the above example).

How add require in JavaScript?

To include the Require. js file, you need to add the script tag in the html file. Within the script tag, add the data-main attribute to load the module. This can be taken as the main entry point to your application.


Video Answer


2 Answers

Instantiating what is returned by require.

new should be used when you're instantiating a new instance of a class or function, and not otherwise. You almost certainly don't want to instantiate an instance of require.

However, if you want to instantiate an instance of a class/function returned by require, you could probably do something like:

var myModuleInstance = new (require('my-module'));

The extra containing parentheses means you're instantiating the returned object, not directly instantiating require.

like image 71
Jason Avatar answered Sep 27 '22 21:09

Jason


In terms of JavaScript, they're not the same. In terms of require() as a function? It seems so, but I'd still advise against doing it.

Using new does a lot under the hood. require() will be affected by the use of new, as it's internal value of this will change.

var foo = {
    path: '/foo/bar/',

    require: function (module) {
        console.log(this.path + module);
    }
};

foo.require('baz'); // logs /foo/bar/baz
new foo.require('trev'); // logs undefinedtrev

Currently require() seems not to use this at all (as it's behaviour doesn't change whether you change the value of this or not). However, this isn't guaranteed to be the case in the future; it isn't documented.

TL;DR: don't use it.

like image 30
2 revs Avatar answered Sep 27 '22 22:09

2 revs