Getting Started with Node.js and npm
Learn the basics of Node.js and npm, and create your first Node.js project.
Introduction to Node.js
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine that allows developers to create scalable and high-performance server-side applications. To get started with Node.js, you need to have it installed on your computer.
Step 1: Install Node.js and npm
You can download the latest version of Node.js from the official Node.js website. Once installed, you can verify that Node.js and npm (the package manager for Node.js) are working by running the following commands in your terminal:
node -v
npm -v
Step 2: Create a New Node.js Project
Create a new directory for your project and navigate to it in your terminal. Then, run the following command to create a new npm project:
npm init -y
This will create a package.json file in your project directory.
Step 3: Install Dependencies
For this example, we will install the express framework, which is a popular choice for building web applications with Node.js. Run the following command to install express:
npm install express
Step 4: Create a Simple Web Server
Create a new file called app.js and add the following code to it:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
This code creates a simple web server that listens on port 3000 and responds with 'Hello World!' when you navigate to the root URL.
Step 5: Run the Application
Run the application by executing the following command in your terminal:
node app.js
Open a web browser and navigate to http://localhost:3000 to see the 'Hello World!' message.