Project Setup & Modules Flashcards
How to setup a Node.js project?
- Install Node.js
- Create a directory for the project.
- Open a terminal and run npm init -y (-y flags to use default settings)
- Create a file app.js
- Run Node.js application using node app.js
What is NPM? What is the role of node_modules folder?
NPM is a tool that help us manage dependencies of our project.
node_modules folder contains all the dependencies of the Node.js app. These dependencies are basically libraries or modules that other people built.
What is the role of package.json file in Node?
It is a central manifest for Node.js projects.
Contains the project metadata (information about the project).
It also contains the dependencies of the project that are installed when running npm install and we can configure some aliases for scripts we want to run.
Lastly, it also contains the project configuration, such as type, which node version, etc.
What are modules in Node? What is the difference between a function & module?
A module contains specific functionality that can be reused within a Node.js app. Ideally, each JavaScript file is a single module.
The difference between functions and modules is that functions are a set of instructions with a strict syntax, while module encapsulates functionality.
How many ways are there to Export a module?
Using module.exports (CommonJS syntax)
module.exports.myFunction = myFunction;
module.exports.aConst = aConst;
module.exports.myObject = myObject;
Directly using the exports object (CommonJS syntax)
exports.sayHello = function(name){
console.log(“Hello, “, name);
}
Using the keyword export (ES Modules syntax).
Import syntax
CommonJS: const { myFunction } = require(‘./myModule’)
ES Modules: import { myFunction } from ‘./myModule’
Loading Behavior:
CommonJS loads modules synchronously and can be dynamic
ES Modules are statically analyzed at parse time and support asynchronous loading
What happens if you don’t export the module?
It won’t be available to be imported in other modules/files.
What is module wrapper function?
Everything we write inside a .js file get’s automatically converted/wrapped by Node into a IIFE before it is executed.
What are the types of modules in Node?
Built-in Modules (Core Modules)
Local Modules (User defined modules)
Third-Party Modules (Libraries, external packages);