Require file internally in node.js

How do you need a file internally in node.js? For example. api.js:

var api = require(./api.js);

      

What's the best practice for this?

+3


source to share


1 answer


You can do it completely. Try this for example (in a file named a.js

):

exports.foo = 'foo';

var a = require('./a');

console.log(a);

exports.bar = 'bar';

console.log(a);

      

At the point where it is executed require

, it will return the module a

as it exists at the point where it require

runs, so the field foo

will be defined but not bar

.

There is no point in doing this. You use require

to inject into your current scope an object that would not otherwise be available (namely a module). But you don't need to do this to access the module you are currently in: it is already fully available.



This code works because Node has rules for handling circular dependencies . And here you have a module that cyclically depends on itself. Instead of going into an infinite loop, Node has a require

return module built up to that point: a partial module. And modules in a circular dependency must be designed to cope with the fact that they can receive partial modules.

Cyclic dependencies should be avoided as much as possible. In most cases, this means refactoring modules to avoid interdependencies by moving functionality into one or more new modules.

So, it's best not to do this in the first place.

+8


source







All Articles