Path, NPM, Creating Node Project and Third Party Packages in NodeJs

 

1. Core Modules

The Core Modules are inbuilt in Node JS.

Some of the most commonly used are:

ModuleDescription
pathHandles file paths
fsHandles the file system
urlParses the URL strings

1.1 Path

The path module provides utilities for working with file and directory paths. It can be accessed using:

const path = require("path");
JAVASCRIPT

Example:

//index.js
const path = require("path");
const filePath = path.join("users", "ravi", "notes.txt");
console.log(filePath);
JAVASCRIPT

Output

root@123# node index.js
users/ravi/notes.txt
Note

Many developers prefer Common JS Modules to ES6 syntax as ES6 syntax is in the experimental phase.

2. Package

A package is a directory with one or more modules grouped.

2.1 Node Package Manager (NPM)

NPM is the package manager for the Node JS packages with more than one million packages.

It provides a command line tool that allows you to publish, discover, install, and develop node programs.

2.1.1 CLI

NPM CLI sets up the Node JS Project to organize various modules and work with third-party packages.

CommandDescription
npm init -y
Initializes a project and creates a package.json file
npm install <package-name> --save
Installs the third-party packages

3. Steps to create a Node JS Project

Run the below commands in the terminal.

  1. Create a new directory/folder.

mkdir myapp

  1. Move into the created folder.

cd myapp

  1. Initialize the project.

npm init -y

4. Third-Party Packages

The Third-Party Packages are the external Node JS Packages.

They are developed by Node JS developers and are made available through the Node ecosystem.

4.1 date-fns

It is a third-party package for manipulating JavaScript dates in a browser & Node.js.

Installation Command:

npm install date-fns --save

4.1.1 addDays

It adds the specified number of days to the given date.

Example:

//index.js
const addDays = require("date-fns/addDays");
const result = addDays(new Date(2021, 0, 11), 10);
console.log(result);
JAVASCRIPT

Output

root@123# node index.js
2021-01-21T00:00:00.000Z
Note

While creating the

Date()
object, we have to provide the month index from (0-11), whereas we will get the output considering Jan=1 and Dec=12.

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form