max-mapper / art-of-node

:snowflake: a short introduction to node.js
https://github.com/maxogden/art-of-node#the-art-of-node
Other
9.79k stars 856 forks source link

Question on "require" #51

Closed yolapop closed 8 years ago

yolapop commented 9 years ago

Hi, I'm a beginner, just a couple of questions :)

When you call require('some_module') in node here is what happens:

  1. if a file called some_module.js exists in the current folder node will load that, otherwise:
  2. node looks in the current folder for a node_modules folder with a some_module folder in it
  3. if it doesn't find it, it will go up one folder and repeat step 2

Isn't it needed to add ./ in require to find local modules? i.e. if I have filter.js in my current directory and I want to load it as a module I would require('./filter').

Also, reading this http://www.bennadel.com/blog/2169-where-does-node-js-and-require-look-for-modules.htm

var utils = require( "utils" );

If the given module is not a core module, Node.js will then begin to search for a directory named, "node_modules". It will start in the current directory (relative to the currently-executing Javascript file in Node) and then work its way up the folder hierarchy, checking each level for a node_modules folder.

Node.js will perform a hierarchical directory search for "node_modules" and "utils" in the following ways:

./node_modules/utils.js ./node_modules/utils/index.js ./node_modules/utils/package.json

I'd like some clarification because the explanation above seems different with yours. Thank you.

max-mapper commented 9 years ago

@yolapop Hi, thanks for the great question.

Isn't it needed to add ./ in require to find local modules?

Yes, you are absolutely correct here. Now that you point that out, I think I should probably update that section as it is currently inaccurate.

Node.js will perform a hierarchical directory search for "node_modules" and "utils" in the following ways:

./node_modules/utils.js ./node_modules/utils/index.js ./node_modules/utils/package.json

I don't think this is technically accurate either... the directory search would look like this instead:

hope this helps!

max-mapper commented 9 years ago

@yolapop also I can highly recommend this nodeschool workshop https://github.com/npm/how-to-npm

yolapop commented 9 years ago

Thanks for the answer and recommendation!

On Sun, Mar 22, 2015, 11:41 PM Max Ogden notifications@github.com wrote:

@yolapop https://github.com/yolapop also I can highly recommend this nodeschool workshop https://github.com/npm/how-to-npm

— Reply to this email directly or view it on GitHub https://github.com/maxogden/art-of-node/issues/51#issuecomment-84651470.