Как правильно установить node js
Перейти к содержимому

Как правильно установить node js

  • автор:

Downloads

Download the Node.js source code or a pre-built installer for your platform, and start developing today.

Recommended For Most Users
Latest Features

Windows Installer (.msi) 32-bit 64-bit ARM64
Windows Binary (.zip) 32-bit 64-bit ARM64
macOS Installer (.pkg) 64-bit / ARM64
macOS Binary (.tar.gz) 64-bit ARM64
Linux Binaries (x64) 64-bit
Linux Binaries (ARM) ARMv7 ARMv8
Source Code node- v20.11.0 .tar.gz

Additional Platforms

Docker Image Official Node.js Docker Image
Linux on Power LE Systems 64-bit
Linux on System z 64-bit
AIX on Power Systems 64-bit
  • Signed SHASUMS for release files(How to verify)
  • All download options
  • Installing Node.js via package manager
  • Previous Releases
  • Nightly builds
  • Unofficial builds
  • Building Node.js from source on supported platforms
  • Installing Node.js via binary archive
  • Install on Windows Subsystem for Linux (WSL)

Copyright OpenJS Foundation and Node.js contributors. All rights reserved. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them.

How to install Node.js

Node.js can be installed in different ways. This post highlights the most common and convenient ones. Official packages for all the major platforms are available at https://nodejs.org/download/.

One very convenient way to install Node.js is through a package manager. In this case, every operating system has its own. Other package managers for MacOS, Linux, and Windows are listed in https://nodejs.org/download/package-manager/

nvm is a popular way to run Node.js. It allows you to easily switch the Node.js version, and install new versions to try and easily rollback if something breaks. It is also very useful to test your code with old Node.js versions.

See https://github.com/nvm-sh/nvm for more information about this option.

In any case, when Node.js is installed you’ll have access to the node executable program in the command line.

Copyright OpenJS Foundation and Node.js contributors. All rights reserved. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them.

Installing Node.js via package manager

Note: The packages on this page are maintained and supported by their respective packagers, not the Node.js core team. Please report any issues you encounter to the package maintainer. If it turns out your issue is a bug in Node.js itself, the maintainer will report the issue upstream.

Alpine Linux

Node.js LTS and npm packages are available in the Main Repository.

apk add nodejs npm 

Node.js Current can be installed from the Community Repository.

apk add nodejs-current 

Android

Android support is still experimental in Node.js, so precompiled binaries are not yet provided by Node.js developers.

However, there are some third-party solutions. For example, Termux community provides terminal emulator and Linux environment for Android, as well as own package manager and extensive collection of many precompiled applications. This command in Termux app will install the last available Node.js version:

pkg install nodejs 

Currently, Termux Node.js binaries are linked against system-icu (depending on libicu package).

Arch Linux

Node.js and npm packages are available in the Community Repository.

pacman -S nodejs npm 

CentOS, Fedora and Red Hat Enterprise Linux

Node.js is available as a module called nodejs in CentOS/RHEL 8 and Fedora.

dnf module install nodejs:stream> 

where corresponds to the major version of Node.js. To see a list of available streams:

dnf module list nodejs 

For example, to install Node.js 18:

dnf module install nodejs:18/common 

Alternatives

These resources provide packages compatible with CentOS, Fedora, and RHEL.

  • Node.js snaps maintained and supported at https://github.com/nodejs/snap
  • Node.js binary distributions maintained and supported by NodeSource

Debian and Ubuntu based Linux distributions

Alternatives

Packages compatible with Debian and Ubuntu based Linux distributions are available via Node.js snaps.

fnm

Fast and simple Node.js version manager built in Rust used to manage multiple released Node.js versions. It allows you to perform operations like install, uninstall, switch Node versions automatically based on the current directory, etc. To install fnm, use this install script.

fnm has cross-platform support (macOS, Windows, Linux) & all popular shells (Bash, Zsh, Fish, PowerShell, Windows Command Line Prompt). fnm is built with speed in mind and compatibility support for .node-version and .nvmrc files.

FreeBSD

The most recent release of Node.js is available via the www/node port.

Install a binary package via pkg:

pkg install node 

Or compile it on your own using ports:

cd /usr/ports/www/node && make install 

Gentoo

Node.js is available in the portage tree.

emerge nodejs 

IBM i

LTS versions of Node.js are available from IBM, and are available via the ‘yum’ package manager. The package name is nodejs followed by the major version number (for instance, nodejs12 , nodejs14 etc)

To install Node.js 14.x from the command line, run the following as a user with *ALLOBJ special authority:

yum install nodejs14 

Node.js can also be installed with the IBM i Access Client Solutions product. See this support document for more details

macOS

Download the macOS Installer directly from the nodejs.org web site.

If you want to download the package with bash:

curl "https://nodejs.org/dist/latest/node-$VERSION:-$(wget -qO- https://nodejs.org/dist/latest/ | sed -nE 's|.*>node-(.*)\.pkg.*|\1|p')>.pkg" > "$HOME/Downloads/node-latest.pkg" && sudo installer -store -pkg "$HOME/Downloads/node-latest.pkg" -target "/" 

Alternatives

Using Homebrew:

brew install node 

Using MacPorts:

port install nodejsmajor version> # Example port install nodejs7 

Using pkgsrc:

Install the binary package:

pkgin -y install nodejs 

Or build manually from pkgsrc:

cd pkgsrc/lang/nodejs && bmake install 

n

n is a simple to use Node.js version manager for Mac and Linux. Specify the target version to install using a rich syntax, or select from a menu of previously downloaded versions. The versions are installed system-wide or user-wide, and for more targeted use you can run a version directly from the cached downloads.

See the homepage for install methods (bootstrap, npm, Homebrew, third-party), and all the usage details.

If you already have npm then installing n and then the newest LTS node version is as simple as:

npm install -g n n lts 

NetBSD

Node.js is available in the pkgsrc tree:

cd /usr/pkgsrc/lang/nodejs && make install 

Or install a binary package (if available for your platform) using pkgin:

pkgin -y install nodejs 

Nodenv

nodenv is a lightweight node version manager, similar to nvm . It’s simple and predictable. A rich plugin ecosystem lets you tailor it to suit your needs. Use nodenv to pick a Node version for your application and guarantee that your development environment matches production.

Nodenv installation instructions are maintained on its Github page. Please visit that page to ensure you’re following the latest version of the installation steps.

nvm

Node Version Manager is a bash script used to manage multiple released Node.js versions. It allows you to perform operations like install, uninstall, switch version, etc. To install nvm, use this install script.

On Unix / OS X systems Node.js built from source can be installed using nvm by installing into the location that nvm expects:

env VERSION=`python tools/getnodeversion.py` make install DESTDIR=`nvm_version_path v$VERSION` PREFIX="" 

After this you can use nvm to switch between released versions and versions built from source. For example, if the version of Node.js is v8.0.0-pre:

nvm use 8 

Once the official release is out you will want to uninstall the version built from source:

nvm uninstall 8 

nvs

Windows

The nvs version manager is cross-platform and can be used on Windows, macOS, and Unix-like systems

To install nvs on Windows go to the release page here and download the MSI installer file of the latest release.

You can also use chocolatey to install it:

choco install nvs 
macOS,UnixLike

You can find the documentation regarding the installation steps of nvs in macOS/Unix-like systems here

Usage

After this you can use nvs to switch between different versions of node.

To add the latest version of node:

nvs add latest 

Or to add the latest LTS version of node:

nvs add lts 

Then run the nvs use command to add a version of node to your PATH for the current shell:

$ nvs use lts PATH -= %LOCALAPPDATA%\nvs\default PATH += %LOCALAPPDATA%\nvs\node\14.17.0\x64 

To add it to PATH permanently, use nvs link :

nvs link lts 

OpenBSD

Node.js is available through the ports system.

/usr/ports/lang/node 

Using pkg_add on OpenBSD:

pkg_add node 

openSUSE and SLE

Node.js is available in the main repositories under the following packages:

  • openSUSE Leap 15.2: nodejs10 , nodejs12 , nodejs14
  • openSUSE Tumbleweed: nodejs20
  • SUSE Linux Enterprise Server (SLES) 12: nodejs10 , nodejs12 , and nodejs14 (The «Web and Scripting Module» must be enabled.)
  • SUSE Linux Enterprise Server (SLES) 15 SP2: nodejs10 , nodejs12 , and nodejs14 (The «Web and Scripting Module» must be enabled.)

For example, to install Node.js 14.x on openSUSE Leap 15.2, run the following as root:

zypper install nodejs14 

Different major versions of Node can be installed and used concurrently.

SmartOS and illumos

SmartOS images come with pkgsrc pre-installed. On other illumos distributions, first install pkgsrc, then you may install the binary package as normal:

pkgin -y install nodejs 

Or build manually from pkgsrc:

cd pkgsrc/lang/nodejs && bmake install 

Snap

Node.js snaps are available as node on the Snap store.

Solus

Solus provides Node.js in its main repository.

sudo eopkg install nodejs 

Void Linux

Void Linux ships Node.js stable in the main repository.

xbps-install -Sy nodejs 

Windows

Download the Windows Installer directly from the nodejs.org web site.

Alternatives

Using Winget:

winget install OpenJS.NodeJS # or for LTS winget install OpenJS.NodeJS.LTS 

After running one of the two commands above, it may be necessary to restart the terminal emulator before the node CLI command becomes available.

Using Chocolatey:

cinst nodejs # or for full install with npm cinst nodejs.install 

Using Scoop:

scoop install nodejs # or for LTS scoop install nodejs-lts 

z/OS

IBM® SDK for Node.js — z/OS® is available in two installation formats, SMP/E and PAX. Select the installation format that applies to you:

  • Installing and configuring SMP/E edition of Node.js on z/OS
  • Installing and configuring PAX edition of Node.js on z/OS

Copyright OpenJS Foundation and Node.js contributors. All rights reserved. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them.

Установка Node.js на Windows и macOS

Node.js помогает JavaScript взаимодействовать с устройствами ввода-вывода через свой API и подключать разные внешние библиотеки (главное, делать это без фанатизма).

Перейдите на официальный сайт и скачайте последнюю стабильную версию с припиской LTS. На сайте есть версии и для Windows, и для macOS. Выглядит это примерно так:

После загрузки запустите установщик и установите Node.js как любую другую программу (то есть Далее—Далее—Далее). Чтобы проверить, что Node.js установилась, и узнать версию, откройте терминал и введите две команды node -v и npm -v .

Проверка версии node.js. На скриншоте Node.js 18.16.0 и npm 9.5.1.

Вот и всё — можете пользоваться.

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

Читать дальше

Объект URL в JavaScript: полный разбор

Объект URL в JavaScript: полный разбор

Объект URL в JavaScript представляет URL-адрес и предоставляет удобные методы для работы с ним. Он позволяет анализировать, конструировать и декодировать URL-адреса.

Создать объект URL можно двумя способами:

Конструктор URL() — самый распространённый способ, в котором вы передаёте любой URL в виде строки в качестве аргумента.

const url = new URL("https://www.example.com/path?query=123#hash"); 

Использование window.location — это глобальный объект в браузерах, который содержит информацию о текущем URL.

const currentUrl = new URL(window.location.href); 
  • 23 января 2024

Генерация QR-кодов на JS в 4 шага. Node.js + qrcode

Генерация QR-кодов на JS в 4 шага. Node.js + qrcode

Сегодня сделаем простой REST API на Node.js и Express, который будет генерировать QR-коды для любой ссылки. Если у вас ещё не установлены Node.js и npm , установите их с официального сайта.

  • 22 ноября 2023

ChatGPT не справляется

ChatGPT не справляется

Притворитесь нейросетью и решите 101 задачку по JavaScript как можно быстрее.

  • 2 ноября 2023

Знакомство с JavaScript

Знакомство с JavaScript

Теперь, когда вы знаете, как создать структуру веб-страницы с помощью HTML и оформить ее стилями с помощью CSS, пришло время оживить её с помощью JavaScript (JS). JavaScript — это мощный язык программирования, который используется для создания интерактивных и динамических веб-сайтов.

Вы можете добавить JavaScript в ваш HTML-документ двумя способами:

Встроенный JavaScript: непосредственно в HTML-документ, в тегах :

  

Внешний JavaScript: подключение внешнего .js файла к HTML-документу:

  • 1 ноября 2023

Событие onclick в JS на примерах

Событие onclick в JS на примерах

Интерактивность — ключевой компонент любого современного сайта. И одним из наиболее часто используемых событий для создания интерактивности является событие onclick . В этой статье мы подробно разберёмся, что такое событие onclick , как его использовать и приведем примеры применения.

Событие onclick — это событие JavaScript, которое активируется, когда пользователь кликает на определенный элемент страницы. Это может быть кнопка, ссылка, изображение или любой другой элемент, на который можно нажать.

  • 30 октября 2023

Как перевернуть сайт. Самая короткая инструкция

Как перевернуть сайт. Самая короткая инструкция

Не представляем, зачем это может понадобиться, но не могли пройти мимо.

Никакой магии. Мы вызываем JavaScript-функцию rotateBody() , которая применяет свойство transform с значением rotate(180deg) к элементу . Когда вы нажмете на кнопку «Перевернуть», всё, что находится внутри будет повернуто на 180 градусов (то есть, встанет вниз головой)

function rotateBody() < document.body.style.transform = 'rotate(180deg)'; > 

Но такой код повернёт страницу только один раз. Если нужно, чтобы она возвращалась обратно при втором клике, усложним код:

let isRotated = false; function rotateBody() < if (isRotated) < document.body.style.transform = 'rotate(0deg)'; document.body.style.direction = "ltr"; >else < document.body.style.transform = 'rotate(180deg)'; document.body.style.direction = "rtl"; >isRotated = !isRotated; > 

Надеемся, вы прочитали это описание до того, как нажать на кнопку.

  • 25 октября 2023

Как узнать геолокацию: Geolocation API

Как узнать геолокацию: Geolocation API

Geolocation API позволяет сайтам запрашивать, а пользователям предоставлять свое местоположение веб-приложениям. Геолокация может использоваться для выбора города в интернет-магазине, отображения пользователя на карте или навигации в ближайший гипермаркет.

Основной метод Geolocation API — getCurrentPosition() , но есть и другие методы и свойства, которые могут пригодиться.

  • 16 октября 2023

Что такое localStorage и как им пользоваться

Что такое localStorage и как им пользоваться

localStorage — это место в браузере пользователя, в котором сайты могут сохранять разные данные. Это как ящик для хранения вещей, которые не исчезнут, даже если вы выключите компьютер или закроете браузер.

До localStorage разработчики часто использовали cookies, но они были не очень удобны: мало места и постоянная передача данных туда-сюда. LocalStorage появился, чтобы сделать процесс более простым и эффективным.

  • 12 октября 2023

Случайное число из диапазона

Случайное число из диапазона

Допустим, вам зачем-то нужно целое случайное число от min до max . Вот сниппет, который поможет:

function getRandomInRange(min, max)
  1. Math.random () генерирует случайное число между 0 и 1. Например, нам выпало число 0.54 .
  2. (max — min + 1): определяет количество возможных значений в заданном диапазоне. 10 — 0 + 1 = 11 . Это значит, что у нас есть 11 возможных значений (0, 1, 2, . 10).
  3. Math.random () * (max — min + 1): умножает случайное число на количество возможных значений: 0.54 * 11 = 5.94 .
  4. Math.floor (): округляет число вниз до ближайшего целого. Так, Math.floor(5.94) = 5 .
  5. . + min: смещает диапазон так, чтобы минимальное значение соответствовало min . Но в нашем примере, так как min = 0 , это не изменит результат. Пример: 5 + 0 = 5 .
  6. Итак, в нашем примере получилось случайное число 5 из диапазона от 0 до 10.

Чтобы протестировать, запустите:

console.log(getRandomInRange(1, 10)); // Тест 
  • 7 сентября 2023

В чём разница между var и let

В чём разница между var и let

Если вы недавно пишете на JavaScript, то наверняка задавались вопросом, чем отличаются var и let , и что выбрать в каждом случае. Объясняем.

var и let — это просто два способа объявить переменную. Вот так:

var x = 10; let y = 20; 

Переменная, объявленная через var , доступна только внутри «своей» функции, или глобально, если она была объявлена вне функции.

function myFunction() < var z = 30; console.log(z); // 30 >myFunction(); console.log(z); // ReferenceError 

Это может создавать неожиданные ситуации. Допустим, вы создаёте цикл в функции и хотите, чтобы переменная i осталась в этой функции. Если вы используете var , эта переменная «утечёт» за пределы цикла и будет доступна во всей функции.

Переменные, объявленные с помощью let доступны только в пределах блока кода, в котором они были объявлены.

if (true) < let a = 40; console.log(a); // 40 >console.log(a); // ReferenceError 

В JavaScript блок кода — это участок кода, заключённый в фигурные скобки <> . Это может быть цикл, код в условном операторе или что-нибудь ещё.

if (true) < let blockScoped = "Я виден только здесь"; console.log(blockScoped); // "Я виден только здесь" >// здесь переменная blockScoped недоступна console.log(blockScoped); // ReferenceError 

Если переменная j объявлена в цикле с let , она останется только в этом цикле, и попытка обратиться к ней за его пределами вызовет ошибку.

  • 30 августа 2023

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *