0
votes

Most languages use 'import' directives to load other module code, like java -

import a.b.c

elisp -

(load a)

python -

from a import b

But, why does nodejs use a variable expression to load other module functions like

var a = require('a')

i see, most IDEs for javascript like tern.js-emacs, nodeclipse are not able to do source code lookup (for loaded modules) properly because the IDE has to run the code (or) do eval to find out, what properties a loaded module object contains.

1
ECMAScript 5.1 (es5.github.io) is the language Node.js runs. It doesn't have import. ES6 does and when V8 supports it, node will support it. In the mean time there are ES6 -> ES5 converters that allow you to use import in JS today if you like. - generalhenry
so that you can use the variable to reference the object returned. a.someMethodOfA(); for instance. - Todd

1 Answers

0
votes

You could say JS belongs to a category of languages where the idea that everything is an object on equal footing is part of the "philosophy" that has guided its development. Node's require is a function (an object) supplied by the environment, as is the module object. This pattern is called the Common JS format.

You actually don't have to assign the result of the require function to a variable. It's rare in practice, but the node module you're calling on could just be invoked to cause an action to take place, for example one might require sugar.js which alters some of the native objects but has no methods of its own to offer, so there would be no point in assigning the return value (which is the module.exports object that was supplied during that module's execution).

A more common example of not assigning a module to a variable is when one uses require just to grab some property off the module -- e.g. var x = require('module').methodOfInterest. Similarly, some modules return a constructor, so you may sometimes see var instance = new (require('ConstructorModule'))(options) (which is ugly in my opinion; requires should generally be grouped at the top of a file and acted on only afterwards).

Note: There's really no concrete answer to your question so odds are high that it will get closed as SO-inappropriate.