Node JS -Ultra fast applications using Node js - Node - Node JS tutorial - Nodejs
When we do this, Node.js will search on our disk for a file called http.js. Likewise, if we ask for the "url" module, Node.js will search for a file called url.js.
- They are hidden in a nice and warm place on your disk, their location is of no interest to us.
- Given that they are part of the core of Node.js, they are always available.
- The modules are therefore simply .js files. If we want to create a module, let’s say the "test" module, we need to create a test.js file in the same folder and call for it like this:
- Don’t put the .js extension in the require()!
- It’s a relative path. If the module is in the parent folder, we can include it like this:
- What if I don’t want to put in a relative pathway? Can’t I just do require('test')?
- You can! You need to put your test.js file in a sub-folder called "node_modules". It’s a Node.js standard:
Learn Nodejs - Nodejs tutorial - nodejs application - Nodejs examples - Nodejs programs
- Note that if the node_modules file doesn’t exist, Node.js will go to search in a file that has the same name higher up in the tree. This way, if your project is found in the /home/mateo21/dev/nodejs/projet folder, it will go and find a file named:
- The start of the file doesn’t contain anything new. We’re creating functions that we’re placing in the variables. From which the var sayHello = function() comes from.
- Then comes the new part, we’re exporting functions so they are usable externally: exports.sayHello = sayHello;. Note that we could have just done this instead:
- All the functions that you don’t export in your module file will remain private. They won’t be able to be called for externally.
- However, they will be able to be used by other functions within your module.
- Now, in your app’s main file (ex: app.js), you can call for these functions from the module!
- require() returns an object that contains the functions that you exported in your module. We store this object in a variable of the same name mymodule (but we could have given it any other name), like in the next figure.
Learn Nodejs - Nodejs tutorial - nodejs application architecture - Nodejs examples - Nodejs programs