3

How do you require a file within itself in node.js? E.g. api.js:

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

What is the best practice for doing this?

6
  • 4
    The best practice is to not do this. Commented Nov 5, 2014 at 23:33
  • Please elaborate . . . Commented Nov 5, 2014 at 23:35
  • Obviously you can just define functions but is that the only reason this is ill-advised? Commented Nov 5, 2014 at 23:35
  • 1
    What problem is this supposed to solve? Commented Nov 5, 2014 at 23:37
  • 2
    The point of require() is to load a module. But, if you're already in the module, it is already loaded, so there really is no point to try to load it again from within itself. Likely all you need to do is to call a function within your module, but since you haven't explained what problem you're really trying to solve, we can't provide more specific help. Commented Nov 5, 2014 at 23:40

1 Answer 1

10

You can totally do it. Try this, for instance (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 require executes, it will return the module a as it exists at the point where require runs so the field foo will be defined but not bar.

There's no point to doing this though. You use require to bring into your current scope an object which would otherwise not 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.

The code above works because Node has rules to handle cyclic dependencies. And here you have a module which is cyclicly dependent on itself. Rather than go into an infinite loop of requires, Node has require return the module as built up to that point: a partial module. And the modules in a cyclic dependency have to be designed to handle the fact that they may get partial modules.

Cyclic dependencies are to be avoided as much as possible. Most of the time this means refactoring the modules to avoid the mutual dependency by moving functionality into one or more new modules.

So, again, the best practice is to not do this in the first place.

Sign up to request clarification or add additional context in comments.

2 Comments

yeah I am writing a program that could potential be given an argument from the command line that represents the same file that is about to run, and so the file could potential require itself, and it happened, but it didn't re-require itself as you say
in other words: node index.js --files index.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.