Search code examples
javascriptnode.jsrequire

Does require('./bar') try to load a file named 'bar' first or 'bar.js' first?


Quoting from the article at https://medium.freecodecamp.org/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8 below:

We can natively require JSON files and C++ addon files with the require function. You don’t even need to specify a file extension to do so.

If a file extension was not specified, the first thing Node will try to resolve is a .js file. If it can’t find a .js file, it will try a .json file and it will parse the .json file if found as a JSON text file. After that, it will try to find a binary .node file. However, to remove ambiguity, you should probably specify a file extension when requiring anything other than .js files.

Here is my little experiment that seems to contradict what is written above.

$ cat foo.js
console.log('I am foo.js!')
require('./bar')
$ cat bar.js
console.log('I am bar.js!')
$ cat bar
console.log('I am bar!')
$ node foo.js
I am foo.js!
I am bar!
$ node bar
I am bar!

The experiment shows that if I do not specify the .js extension name, i.e. I import only bar or try to run only bar, then the first thing Node tries to do is to find a file named exactly as bar. Therefore, it contradicts the following statement from the quoted article.

If a file extension was not specified, the first thing Node will try to resolve is a .js file.

Is the quoted article incorrect or am I misunderstanding something?


Solution

  • The article is incorrect. From the official documentation:

    LOAD_AS_FILE(X)

    1. If X is a file, load X as JavaScript text. STOP
    2. If X.js is a file, load X.js as JavaScript text. STOP
    3. If X.json is a file, parse X.json to a JavaScript Object. STOP
    4. If X.node is a file, load X.node as binary addon. STOP