How does require() work and why I don't need a relative path for express?


#1

Question

How does require() work and why I don’t need a file path for express?

Answer

As we may remember, require() is a node method, Node being a runtime-environment (think of an emulator for the browser’s javascript functionality), by itself node is also comprised of multiple libraries and it has its own existing methods.

So we can use require() anywhere while working within Node. We know that we are working with Node when we create an app environment using npm and creating a package.json file.

Now, Node has a very specifically structured module system, each module is a library that helps us run node or helps us build on top of the existing environment ( like we do when we npm install express from the command line). It is because of that structure that node has already in memory the location where the node modules need to be and are.

Based on that knowledge, the require() method only needs a file name (identification) that will differentiate one module from others, in the case of express, since it is a library module require() will know that it is in the node modules directory and so it only needs the identification (aka the string 'express'), versus trying to require a local file that we have created, which in that case we need a relative file path.

In itself the require() method checks if the string passed is a relative path or not, if it is not, it will use the node modules directory to find a matching expression to the passing string and retrieve it. If it is a file path though, it will check if it has a file extension, here, not having one is like knowing that it is a JavaScript file (.js) and then it will retrieve its value from the given path and return it.


FAQ: Code Challenges - Code Challenge