Хочешь проверить свои знания по JS?
Подпишись на наш канал с тестами по JS в Telegram!
×
Веб-разработчику, работающему хоть над фронтендом, хоть над бэкендом, понадобится установить Node.js в его систему.
Но, используя обычную команду sudo apt install nodejs, можно установить очень старую версию Node, что может привести к проблемам.
Поэтому вы, скорее всего, захотите установить конкретную версию, а для этого понадобится другая команда. Она должна установить LTS-версию Node (версию с долговременной поддержкой), предпочтительную для нужд разработчиков.
В этой статье я покажу вам, как установить последнюю LTS-версию Node в операционной системе Ubuntu.
Этот процесс подходит для любой ОС на базе Debian (Ubuntu, Mint, Zorin, Debian, Elementary OS и т. д.). Также не имеет значения, устанавливаете вы Node в основную или во вторичную ОС, в WSL в Windows или в ОС на виртуальной машине (VMware Workstation, VirtualBox и т. п.).
Видеотуториал
Я также создал полное видео, где показал весь процесс установки Node в Ubuntu шаг за шагом. Посмотреть можно здесь:
Следуя инструкциям из этой статьи (или видео), вы автоматически установите последнюю LTS-версию Node. На момент написания этой статьи последняя версия — 18.18.2.
От редакции Techrocks: вас также может заинтересовать статья «Лучшие проекты на Node.js для начинающих».
Обновите вашу операционную систему
Для начала нужно заранее установить все обновления. Я предпочитаю работать в терминале, так что и обновления устанавливаю через него.
От редакции Techrocks: обратите внимание на статью «5 приемов использования терминала Unix для ускорения разработки «.
Для обновления всех нужных пакетов до последних версий используйте команду sudo apt update. Когда у вас запросят пароль, введите его.
Теперь запустите команду sudo apt upgrade -y, чтобы проапгрейдить пакеты.
Установите CURL
Для установки Node мы будем использовать Node Version Manager (NVM). Установка Node и npm через NVM дает многие преимущества, в том числе позволяет устанавливать в систему несколько версий Node.js сразу.
Сначала нужно установить curl (если он еще не установлен в системе). Воспользуйтесь для этого командой sudo apt install curl -y.
Как установить Node.js
Переходим к пошаговому руководству по установке Node. Следуйте нашим инструкциям, и вы успешно установите Node.js в свою систему.
Установите Node Version Manager (NVM)
Для установки NVM используйте следующую команду:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
При запуске этой команды curl скачивает установочный скрипт NVM по указанному адресу. После этого bash выполняет этот скрипт для установки NVM.
Активируйте NVM
Для активации NVM используйте команду source ~/.bashrc.
Установите последнюю LTS-версию Node
Для установки Node введите команду nvm install —lts.
По умолчанию будет установлена последняя версия с долговременной поддержкой.
Сделайте LTS-версию дефолтной для NVM
Мы установили последнюю LTS-версию Node, а теперь нужно установить версию NVM по умолчанию. Воспользуйтесь для этого следующей командой, указав текущую последнюю версию: nvm alias default 18.18.2.
Если ваша LTS-версия имеет номер 24.1.2, тогда команда будет выглядеть так: nvm alias default 24.1.2.
Убедитесь, что Node установлен
При помощи следующей команды проверьте, является ли установленная вами версия версией по умолчанию.
node -v npm -v
Как настроить окружение Node.js
После установки Node и NPM нужно настроить окружение Node путем создания проекта.
Создадим директорию (папку), в которой протестируем простой проект Node, типа «Hello World».
mkdir my-node-project
Перейдите в директорию my-node-project при помощи команды cd my-node-project.
Инициализируйте новый проект Node: npm init -y.
Эта команда создаст файл package.json, содержащий метаданные и зависимости вашего проекта. Вот вывод JSON:
И в текстовом виде:
{
«name»: «my-node-project»,
«version»: «1.0.0»,
«description»: «»,
«main»: «index.js»,
«scripts»: {
«test»: «echo «Error: no test specified» && exit 1″
},
«keywords»: [],
«author»: «»,
«license»: «ISC»
}
Теперь запустите настройку при помощи простой команды. Я создам для этого новый файл app.js при помощи текстового редактора nano в терминале.
sudo nano app.js
Когда редактор откроется, наберите в нем следующую строку:
console.log(«Hello, Node.js from Ubuntu!»);
Нажмите Ctrl+O, чтобы сохранить файл. Чтобы сохранить его как app.js, нажмите Enter.
Нажмите Ctrl+X, чтобы вернуться в bash.
Пора проверить вывод и посмотреть, все ли работает. Введите команду node app.js.
Работает!
Мы успешно установили последнюю LTS-версию Node в Ubuntu (или другую ОС на основе Debian).
Спасибо за внимание!
Перевод статьи «How to Install Node.js on Ubuntu – Node Linux Installation Guide».
Запись Как установить Node.js в Ubuntu впервые появилась Techrocks.