Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
Node.js is a powerful JavaScript runtime built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server side, making it a popular choice for building scalable network applications. Node.js is crucial for modern web development, offering an event-driven, non-blocking I/O model that makes it lightweight and efficient. This article will guide you through the process of installing and running Node.js on a Linux system, ensuring you can leverage its capabilities in your development environment.
Examples:
Installing Node.js on Linux
To install Node.js, you can use the NodeSource binary distributions repository. Follow these steps:
Update your package index:
sudo apt update
Install Node.js:
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt-get install -y nodejs
This will install the latest LTS (Long Term Support) version of Node.js.
Verifying the Installation
After installation, you can verify that Node.js and npm (Node Package Manager) are installed correctly by checking their versions:
node -v
npm -v
You should see the version numbers of Node.js and npm printed on your terminal.
Creating a Simple Node.js Application
Create a new directory for your project:
mkdir my-node-app
cd my-node-app
Initialize a new Node.js project:
npm init -y
This command creates a package.json
file with default settings.
Create an index.js
file:
touch index.js
Open index.js
in a text editor and add the following code:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Running the Node.js Application
Run the application using Node.js:
node index.js
Access the application:
Open your web browser and navigate to http://127.0.0.1:3000/
. You should see "Hello World" displayed on the page.
Installing Additional Packages
Install Express.js (a popular web framework for Node.js):
npm install express
Modify index.js
to use Express:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
Run the application again:
node index.js
Access the application:
Open your web browser and navigate to http://localhost:3000/
. You should see "Hello World!" displayed on the page.