require('./bar') 是首先尝试加载名为 'bar' 的文件还是首先加载名为 'bar.js' 的文件?

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

引用下面 https://medium.freecodecamp.org/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8 的文章:

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.

这是我的小实验,似乎与上面写的相矛盾。

$ 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!

实验表明,如果我不指定.js扩展名,即我只导入bar或尝试运行只bar,那么第一个Node 试图做的是找到一个与 bar 完全相同的文件。因此,它与引用文章中的以下声明相矛盾。

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

引用的文章不正确还是我误解了什么?

这篇文章不正确。来自 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