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


quoting article @ https://medium.freecodecamp.org/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8 below:

we can natively require json files , c++ addon files require function. don’t need specify file extension so.

if file extension not specified, first thing node try resolve .js file. if can’t find .js file, try .json file , parse .json file if found json text file. after that, try find binary .node file. however, remove ambiguity, should specify file extension when requiring other .js files.

here little experiment seems contradict written above.

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

the experiment shows if not specify .js extension name, i.e. import bar or try run bar, first thing node tries find file named bar. therefore, contradicts following statement quoted article.

if file extension not specified, first thing node try resolve .js file.

is quoted article incorrect or misunderstanding something?

the article incorrect. the official documentation:

load_as_file(x)

  1. if x file, load x javascript text. stop
  2. if x.js file, load x.js javascript text. stop
  3. if x.json file, parse x.json javascript object. stop
  4. if x.node file, load x.node binary addon. stop

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -