Lecture 2 Notes-3253
Lecture 2 Notes-3253
js
Understanding Module
What is a Module?
A module is a self-contained code that can be easily reused across different parts of
an application. It helps in organizing code and makes it easier to maintain and
understand. In Node.js, there are two syntaxes available to use modules:
CommonJS and ES6 module syntax.
CommonJS Module
CommonJS is the default module system in Node.js that uses the ‘require’ function
to import modules and the ‘module.exports’ object to export them.
In the above example, a module called utils.js exports two functions, add and
subtract, using the module.exports object. They can be used in another file as
follows:
// app.js
const { add, subtract } = require('./utils');
ES6 Module
The ES6 module syntax is a more modern approach that is supported by modern
JavaScript environments, and it employs the "import" and "export" keywords.
In the above example, a module called utils.mjs exports two functions add and
subtract using the export keyword. They can be used in another file as follows:
// app.mjs
In the above example, the add and subtract functions from the utils.mjs module are
imported into the app.mjs file using destructuring and then invoked with arguments 2,
3 and 5, 2 respectively. This would output 5 and 3 to the console.
Note: You must use the .mjs extension for ES6 module files.
Types of Modules
There are three main types of modules in Node.js:
1. Core modules: These are built-in modules in Node.js that provide basic
functionality for tasks like file I/O, networking, and more. They can be
imported and used in your application without installation or configuration.
Here are some common core modules:
● 'fs': The 'fs' module works with the file system, like reading and writing
files.
● 'http': The 'http' module is used for creating HTTP servers and clients.
● 'path': The 'path' module is used for working with file paths.
2. Internal/User-defined/local modules: These are custom modules you create
for your own application. They are created as separate files in your application
and can be imported and used in other parts of your application using either
the CommonJS or ES6 module syntax.
3. Third-party modules: These are modules created by other developers and
published on package registries like npm. They can be installed using a
package manager like npm or yarn and then imported and used in your
application.
Package
A package is a collection of reusable code that can be easily shared and installed in
projects. It usually contains one or more modules, along with other files like
documentation, license information, and configuration files. Packages in Node.js are
usually distributed via the npm registry.
Package Manager
A package manager is a tool that simplifies managing, installing, and updating
packages. In the Node.js ecosystem, the most popular package manager is NPM,
which unofficially stands for Node Package Manager.
NPM allows:
● Installation of packages
● Version Management
● Managing dependencies
● Publishing packages
Nodemon
Nodemon is a popular utility for Node.js development that automatically restarts your
application when file changes are detected. This can save you much time during
development, as you won't have to manually restart your server each time you make
changes.
To install “Nodemon” globally, you can use the following command in the terminal:
npm install -g nodemon
This will download and install “Nodemon” globally on your system. Now, you can use
nodemon to start your application by running:
nodemon app.js
Here, app.js is the entry point of your application. Nodemon will watch for changes in
your code and automatically restart the server when any changes are detected. This
can be a huge time-saver during development.
Understanding Package.json file
Package.json file is a crucial part of any Node.js project and contains metadata
about your project such as its name, version, description, author information,
dependencies, scripts, and other configuration options.
Dependencies listed in package.json can be installed by running the command npm
install in the project directory.
Here's an example of a package.json file for a Node.js project that includes nodemon
as a dev dependency:
{
"name": "my-project",
"version": "1.0.0",
"description": "A cool Node.js project!",
"main": "server.js",
"scripts": {
"start": "node server.js",
"go": "nodemon server.js"
},
"author": "Coding Ninjas",
"dependencies": {
"mongodb": "^5.1.0"
},
"devDependencies": {
"nodemon": "^2.0.22"
}
}
● dependencies: These are the dependencies that are required for the project
to run in a production environment. An example of a dependency could be
MongoDB, which is a popular database system used with Node.js. You can
install MongoDB as a dependency using the following command: npm
install mongodb
Listing dependencies separately can help make it clear which dependencies are
required for the project to run in production, and which are only needed for
development. This can also help with managing dependencies and reducing the size
of the project's node_modules directory.
Understanding package-lock.json
● The package-lock.json file is automatically generated by npm when packages
are installed.
● It contains information about the exact versions of all installed packages and
their dependencies.
● The purpose of package-lock.json is to ensure the same versions of packages
are installed on every environment your project runs in, avoiding unexpected
issues caused by different package versions.
● Without package-lock.json, developers or environments might end up with
different package versions, leading to inconsistent behavior and bugs that are
difficult to reproduce and fix.
Readline module
To read input from the console in Node.js, we can use the built-in Readline module.
Readline is a module that provides an interface for reading data from a Readable
stream (such as process.stdin) on a line-by-line basis.
To use the Readline module, we need to require it at the beginning of our file:
const readline = require('readline');
Here's an example code snippet that takes two inputs from the command line using
Readline module and returns their sum:
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
The readline module exports several functions that we can use to interact with the
console. The most commonly used are:
● readline.createInterface(): This function creates a new Readline interface,
which provides methods for reading input from the console.
● rl.question(): This function displays a prompt to the user and waits for them to
enter a response. The response is then passed to a callback function that we
provide.
● rl.close(): This function closes the Readline interface and frees up resources.
3. Updating a file: If you want to append content to an existing file, use the
fs.appendFileSync() method.
const fs = require('fs');
const path = 'example.txt';
});
Path module
The Path module in Node.js is a built-in module that provides various methods to
work with file paths. It can be used to normalize, join, resolve, and manipulate file
and directory paths.
1. path.join(): This method joins two or more path segments using the
platform-specific separator and returns the combined path.
Here is an example:
Here is an example:
//output:
\home\user\folder\file.txt (on Windows systems)
3. path.extname(): This method returns the extension of the given file path. It
takes a file path as input, and returns the extension (including the dot). If there
is no extension, an empty string is returned.
Here is an example:
const path = require('path');
const ext = path.extname('file.txt');
console.log(ext); // output: .txt
Summarising it
Let’s summarise what we have learned in this module:
● Types of modules and how to use them.
● Package managers and NPM.
● Nodemon and how it can be used for automatic server restarts.
● package.json and package-lock.json files.
● dependencies and devDependencies
● NVM to manage multiple Node.js versions on the same machine.
● Reading data from the console using the readline module.
● File System module, including synchronous and asynchronous
methods for file operations.
● Path module and its usage.
● https://betterprogramming.pub/use-nvm-to-manage-node-js-and-npm-ve
rsions-2bd0d0875f9f
● https://nodejs.org/api/readline.html
● https://nodejs.org/api/fs.html
● https://nodejs.org/api/path.html