custom background image

Como instalar o Node.js em Ubuntu 22.04?


Instalar o Node.js em Ubuntu 22.04?

Objetivo

O Node.js é um dos mais famosos runtime JavaScript assíncrono orientado para eventos. A sua adoção alargada nos últimos anos torna-o numa plataforma inevitável no mundo do desenvolvimento. Para obter mais informações e saber mais sobre as capacidades da plataforma Node.js, consulte a documentação oficial.

Neste tutorial, descobrirá como instalar uma plataforma Node.js na distribuição Linux Ubuntu 22.04.

 

Requisitos

Este tutorial parte do princípio de que dispõe de um Ubuntu 22.04, a correr numa instância de computação OVHcloud, por exemplo. Alguns conhecimentos básicos sobre o seu funcionamento são também necessários. Se não tiver o Ubuntu 22.04, siga este guia para utilizar uma Instância de Computação OVHcloud.

Para instalar o Node.js Manager, é necessário instalar a ferramenta make.

 

Instruções

Neste tutorial, primeiro irá instalar uma plataforma Node.js, depois irá usá-la e, para concluir, irá aprender a alternar entre as diferentes versões instaladas.

Aquando da redação deste tutorial, a última versão LTS do Node.js é a 16.15.x e a última versão GA é a 18.1.x.

 

Um Node Manager para geri-los todos

Antes de instalar o Node.js, é necessário instalar uma ferramenta que permite gerir várias instalações do Node.js. As duas ferramentas mais utilizadas são a nvm e a n. Neste tutorial, utilizaremos a n.

Para instalar a n no Ubuntu, a forma mais fácil é recorrer ao script bash fornecido:

curl -L https://bit.ly/n-install | bash

O resultado deve ser o seguinte:

$ curl -L https://bit.ly/n-install | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   161  100   161    0     0    718      0 --:--:-- --:--:-- --:--:--   718
100 43367  100 43367    0     0  83076      0 --:--:-- --:--:-- --:--:--  225k
===
You are ABOUT TO INSTALL n, the Node.js VERSION MANAGER, in:

  /home/ubuntu/n

Afterwards, THE FOLLOWING Node.js VERSION(S) WILL BE INSTALLED,
and the first one listed will be made active; 
  'lts' refers to the LTS (long-term support) version, 
  'latest' to the latest available version.
  '-' means that *no* version will be installed:

  lts
 
If your shell is bash, bsh, zsh, fish, or pwsh (PowerShell), the relevant 
initialization file will be modified in order to:
 - export environment variable $N_PREFIX.
 - ensure that $N_PREFIX/bin is in the $PATH

Your shell, bash, IS supported, and the following initialization
file will be updated:

   /home/ubuntu/.bashrc

For more information, see https://bit.ly/n-install-repo
===
CONTINUE (y/N)? y
-- Cloning https://github.com/tj/n to '/home/ubuntu/n/n/.repo'...
-- Running local n installation to '/home/ubuntu/n/bin'...
-- Shell initialization file '/home/ubuntu/.bashrc' updated.
-- Installing helper scripts in '/home/ubuntu/n/bin'...
-- Installing the requested Node.js version(s)...
   1 of 1: lts...
  installing : node-v16.15.0
       mkdir : /home/ubuntu/n/n/versions/node/16.15.0
       fetch : https://nodejs.org/dist/v16.15.0/node-v16.15.0-linux-x64.tar.xz
     copying : node/16.15.0
   installed : v16.15.0 (with npm 8.5.5)
=== n successfully installed.
  The active Node.js version is: v16.15.0

  Run `n -h` for help.
  To update n later, run `n-update`.
  To uninstall, run `n-uninstall`.

  IMPORTANT: OPEN A NEW TERMINAL TAB/WINDOW or run `. /home/ubuntu/.bashrc`
             before using n and Node.js.
===

Em seguida, pode testar a sua nova instalação:

n --version

O resultado deve ser o seguinte:

$ n --version
v8.2.0

 

Instalação do Node.js com n

Para instalar a versão LTS do Node.js, digite o seguinte comando:

n lts

O resultado deve ser o seguinte:

$ n lts
   copying : node/16.15.0
   installed : v16.15.0 (with npm 8.5.5)

Em seguida, pode testar a sua nova instalação:

npm --version node --version

O resultado deve ser o seguinte:

$ npm --version
8.5.5

$ node --version
v16.15.0

Se desejar instalar a versão GA mais recente do Node.js:

n current

O resultado deve ser o seguinte:

$ n current
  installing : node-v18.1.0
  mkdir : /home/ubuntu/n/n/versions/node/18.1.0
  fetch : https://nodejs.org/dist/v18.1.0/node-v18.1.0-linux-x64.tar.xz
  copying : node/18.1.0
  installed : v18.1.0 (with npm 8.8.0)

 

Testar a instalação do Node.js

Para testar a sua instalação do Node.js, pode escrever uma aplicação Hello World. Crie um ficheiro HelloWorld.js e cole o código seguinte:

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'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });

Guarde-o e execute-o:

node HelloWorld.js

O resultado deve ser o seguinte:

$ node HelloWorld.js
Server running at http://127.0.0.1:3000/

Para testar o exemplo, execute o seguinte comando:

curl http://127.0.0.1:3000/

O resultado deve ser o seguinte:

$ curl http://127.0.0.1:3000/
👋 Hello World

Já está! Instalou e configurou com sucesso o Node.js em Ubuntu 22.04.

 

Ir mais longe

Consulte as ofertas de instâncias Public Cloud na OVHcloud.