Node.js Basics
Node.js Basics
In this guide, we’ll provide an overview of Node.js, including how to set up a Node.js environment, work with modules, and use npm (Node Package Manager).
What is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime environment that allows you to run JavaScript code on the server-side. It uses the V8 JavaScript engine from Google Chrome to execute code outside the browser.
Setting up a Node.js Environment
Installation: Visit the official Node.js website and download the installer for your operating system. Follow the installation instructions provided.
Checking Installation: Open a terminal or command prompt and run the following command to verify that Node.js and npm are installed:
1 2
node -v npm -v
This will display the installed Node.js version and npm version.
Working with Modules
Node.js uses a module system to organize code into reusable components. Each file in Node.js is treated as a module. You can create your own modules and import built-in or third-party modules using the require
function.
Creating a Module: Create a new JavaScript file (e.g.,
myModule.js
) and define a function or variable:1 2 3 4 5 6 7 8
// myModule.js const greeting = "Hello, "; function greet(name) { console.log(greeting + name); } module.exports = greet;
Using a Module: In another file, use the
require
function to import the module and access its functionality:1 2 3 4
// main.js const myModule = require('./myModule'); myModule('John');
Using npm (Node Package Manager)
npm is the default package manager for Node.js, allowing you to install, manage, and share JavaScript packages and libraries.
Initializing a Project: Navigate to your project directory in the terminal and run the following command to create a
package.json
file:1
npm init
Follow the prompts to set up your project details.
Installing Packages: Use the
npm install
command to install packages locally. For example, to install the Express.js framework:1
npm install express
Using Installed Packages: After installing a package, you can require it in your code just like any other module:
1
const express = require('express');
Managing Dependencies: Update dependencies listed in
package.json
by running:1
npm update
This will update packages to their latest versions based on the version constraints specified in
package.json
.
Node.js, with its module system and npm, provides a powerful platform for building scalable and efficient server-side applications using JavaScript.