This session about Node modules, how to create, how to import, how to pass parameter to it.
An exercise at the end of the session.
github: https://github.com/elbassel/MEAN-Training.git
2. Node Modules
- What is Module? Why Module?
- Creating Module
- Importing Modules
- Pass parameters to module.
- Accessing parent module.
- Passing parameters to a running application
- Exercise
- Bonus exercise.
3. What is Module ?
- A module contains related code into a single file to be reused later.
- A module encapsulates related code into a single unit of code. When creating
a module, this can be interpreted as moving all related functions into a file.
- In Node.js, each file is a separate module.
Why Module ?
- Code organize, Code reuse, Clean code.
What is module? Why module?
4. Creating module
- Create ****.js file.
- Put your code in.
- Expose your functions and variables.
5. Importing a module
- To import greetings module, require it.
- A module is an object you can access it’s functions or fields.
6. Passing Parameter to A module
- Write the return of the module as function
- Pass as many parameters as needed.
- In importing module:
8. Accessing Parent module, Take care
- Node.JS is a single thread built on V8 JavaScript Engine.
- Take care of modules dependency and where you initialize your modules.
- An error occurs
9. Passing parameter to application
- Run app: node app.js param1 param2 param3 ….
- You can consume the parameters through array: process.argv
- process.argv[0]: is node itsellf.
- Process.argv[1]: the running file.
- Your parameters are stored in argv array: starting process.argv[2],
process.argv[3], ...
10. Exercise, very very simple Calculator
- This exercise just to get hands on coding.
- The requirements are:
- Write an application to do the following:
- Accept three parameters as: 3 + 9.
- Parse the input parameters.
- Write 2 modules: on module to do the calculations and the second is the app module.
- Print the output and exit the app.
11. Bonus Exercise
- This exercise is the same as previous, with some modifications.
- You can run the application without passing parameters
- Ask the user a question: Does he want to do some calculations?
- If no, exit the app.
- If yes, let him insert his data, for example: 3 + 9
- Print the output.
- Ask the user the same question again and repeat the above three points
- This link can help: