как установить node js на mac os
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.
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:
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.
CentOS, Fedora and Red Hat Enterprise Linux
Node.js is available as a module called nodejs in CentOS/RHEL 8 and Fedora.
where corresponds to the major version of Node.js. To see a list of available streams:
For example, to install Node.js 12:
For CentOS/RHEL 7 Node.js is available via Software Collections.
Alternatives
These resources provide packages compatible with CentOS, Fedora, and RHEL.
Debian and Ubuntu based Linux distributions
Alternatives
Packages compatible with Debian and Ubuntu based Linux distributions are available via Node.js snaps.
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.
FreeBSD
The most recent release of Node.js is available via the www/node port.
Install a binary package via pkg:
Or compile it on your own using ports:
Gentoo
Node.js is available in the portage tree.
IBM i
To install Node.js 14.x from the command line, run the following as a user with *ALLOBJ special authority:
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:
Alternatives
Using Homebrew:
Using MacPorts:
Using pkgsrc:
Install the binary package:
Or build manually from pkgsrc:
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 (boostrap, 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:
NetBSD
Node.js is available in the pkgsrc tree:
Or install a binary package (if available for your platform) using pkgin:
Nodenv
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.
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:
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:
Once the official release is out you will want to uninstall the version built from source:
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:
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:
Or to add the latest LTS version of node:
Then run the nvs use command to add a version of node to your PATH for the current shell:
To add it to PATH permanently, use nvs link :
OpenBSD
Node.js is available through the ports system.
openSUSE and SLE
Node.js is available in the main repositories under the following packages:
For example, to install Node.js 14.x on openSUSE Leap 15.2, run the following as root:
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:
Or build manually from pkgsrc:
Node.js snaps are available as node on the Snap store.
Solus
Solus provides Node.js in its main repository.
Void Linux
Void Linux ships Node.js stable in the main repository.
Windows
Download the Windows Installer directly from the nodejs.org web site.
Alternatives
Using Chocolatey:
Using Scoop:
В© OpenJS Foundation. All Rights Reserved. Portions of this site originally В© Joyent.
Установка Node.js через пакетный менеджер
Заметка: Пакеты, описанные на этой странице, разрабатываются и поддерживаются соответствующими упаковщиками, а не командой Node.js. Пожалуйста, сообщайте о любых проблемах, с которыми вы сталкиваетесь с конкретным пакетом. Если выяснится, что ваша проблема ― ошибка в самом Node.js, проблема будет передана выше.
Android
Поддержка Android все еще является экспериментальной в Node.js, поэтому предварительно скомпилированные двоичные файлы еще не предоставлены в открытом доступе.
Однако есть и сторонние решения. Например, сообщество Termux предоставляет эмулятор терминала и среду Linux для Android, а также собственный менеджер пакетов и обширную коллекцию многих предварительно скомпилированных приложений. Эта команда в приложении Termux установит последнюю доступную версию Node.js:
В настоящее время двоичные файлы Termux Node.js связаны с system-icu (в зависимости от пакета libicu ).
Arch Linux
Пакеты Node.js и npm доступны в репозитории сообщества.
Дистрибутивы Linux на основе Debian и Ubuntu, пакеты Enterprise Linux/Fedora и Snap
FreeBSD
Самый последний выпуск Node.js доступен через порт www/node.
Установите бинарный пакет через pkg:
Или скомпилируйте свой используя порты:
Gentoo
Node.js доступен в дереве портежей.
NetBSD
Node.js доступен в дереве pkgsrc:
Или установите бинарный пакет (если он доступен для вашей платформы) с помощью pkgin:
Node Version Manager ― это bash-скрипт, используемый для управления несколькими выпущенными версиями Node.js. Он позволяет выполнять такие операции, как установка, удаление, переключение версий и т.д.. Чтобы установить nvm, используйте этот скрипт установки.
В системах Unix/OS X Node.js, созданный из исходного кода, можно установить с помощью nvm путем установки в папку по умолчанию nvm:
После этого вы можете использовать nvm для переключения между выпущенными версиями и версиями построенных из исходного кода. Например, если версия Node.js v8.0.0-pre:
После выхода официального релиза вы захотите удалить встроенную версию:
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:
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:
Or to add the latest LTS version of node:
Then run the nvs use command to add a version of node to your PATH for the current shell:
To add it to PATH permanently, use nvs link :
OpenBSD
Node.js доступен через систему портов.
Использование pkg_add в OpenBSD:
openSUSE и SLE
Node.js доступен в основных репозиториях в следующих пакетах:
Например, чтобы установить Node.js 4.x в openSUSE Leap 42.2, запустите следующее от имени пользователя root:
macOS
Просто загрузите установщик macOS прямо с веб-сайта nodejs.org.
Если вы хотите скачать пакет с bash:
Альтернативы
Использование Homebrew:
Использование MacPorts:
Использование pkgsrc:
Установка бинарных файлов:
Или сборка с помощью pkgsrc:
SmartOS и illumos
Образы SmartOS поставляются с предустановленным pkgsrc. В других дистрибутивах Illumos сначала установите pkgsrc, затем вы сможете установить бинарный пакет как обычно:
Или собрать с помощью pkgsrc:
Solus
Solus предоставляет Node.js в своем основном репозитории.
Void Linux
Void Linux поставляет стабильный файл Node.js в основном репозитории.
Windows
Просто загрузите Установщик Windows прямо с веб-сайта nodejs.org.
Альтернативы
Использование Chocolatey:
Использование Scoop:
В© OpenJS Foundation. All Rights Reserved. Portions of this site originally В© Joyent.
Установка node.js на Mac OS
Node.js, также просто Node — программная платформа для разработчиков.
Для проверки кода на ошибки, часто необходимо наличие на компьютере установленного Node.js.
Что такое Node.js
Node.js – интерпретатор языка JavaScript. Другими словами это программа (написанная на языке C++) умеющая читать js файлы и выполнять их содержимое.
Для того чтобы Node.js прочитал файл, заходим в Терминал, переходим в папку со скриптом js. И там набираем:
Результат обработки файла будет отображен здесь же в консоли.
Установка Node.js
Заходим на официальный сайт и скачиваем стабильную сборку:
nodejs.org
Устанавливаем на компьютер
Node.js будет установлен в папке:
Пакеты Node.js
Пакеты в Node.js это один или несколько JavaScript файлов.
Node имеет свой собственный установщик пакетов (npm). И одновременно с его установкой будет создана папка для них:
Программа для установки пакетов:
Показать список всех установленных пакетов:
Проверить версию установленного Node через Терминал можно так:
Создание пакета package.json
В файле package.json находится информация о приложении, его название, версия, зависимости и прочее. Директория в которой находится файл package.json автоматически становится пакетом Node.js.
Для создания пакета Node.js заходим в любую директорию, где нужно создать такой файл и запускаем в консоле команду:
Читайте также
Кстати, на сайте нет рекламы. У сайта нет цели самоокупаться, но если вам пригодилась информация можете задонатить мне на чашечку кофе в макдаке. Лайкнуть страницу или просто поблагодарить. Карма вам зачтется.
Лучший путь как переустановить Node.Js (Mac/Linux/Windows)
Может быть это хорошее время для удаления их всех и настроить возможность системе переключаться между нодами за секунды, всегда зная количество установленных версий и иметь возможность удалить любые из них одной простой командой.
Обо всем по порядку, мы должны удалить старые версии ноды и все связанное с этим. Вы счастливчик, если вы установили прошлые версии с помощью Homebrew. Метод Homebrew это один из простейших вариантов для установки и удаления ноды на маке.
Напишите эту команду в терминале. Brew удалит все установленные версии Node.Js
После этого, лучше всего, запустить brew cleanup, это удалит все неиспользуемые зависимости и папки.
Если ваша Node.js была установлена по другому, это не проблема. Вы можете удалить вручную. Есть куча папок, они могут быть удалены одна за одной через файндер или терминал.
Список папок, где находятся Node.js и npm
В случае, если вы не хотите вручную искать и удалять все эти папки и файлы, вы можете ввести одну простую команду в терминал:
Эта команда не трогает вашу домашнюю директорию, так что в дальнейшем вы можете сами решить, что делать с сохранившимися файлами.
Сейчас мы можем удалить все глобальные пакеты, установленные с npm
После всех этих команд, Node.js и npm будут полностью удалены с вашего компьютера.
После очистки, мы можем продолжить с установкой новой версии Node.js. Но мы сделаем это не прямым путем. Потому что если мы сделаем это по обычному, мы все еще будем иметь ту же проблему с кучей версий в будущем.
Для решения этой проблемы, мы должны установить дополнительную маленький скрипт: NVM
Скачать и установить данный скрипт мы можем с помощью следующей команды:
Конечно, это может быть установлено вручную. Вы нужно склонировать репозиторий и добавить необходимы файлы в PATH. Детальная инструкция описана в NVM ReadMe. Это будет полезно если вам нужно использовать NVM в CI пайплайн. Я бы рекомендовал добавить NVM в Docker image, который использует ваш пайплайн.
Не забудьте перезапустить окно терминала для обновления переменных окружения
Мы почти закончили. Сейчас мы легко можем установить любую версию Node.js. Для примера, эта команда установит самую свежую версию:
Если вы хотите установит LTS версию, но с последней версией npm, сделайте следующее:
Для того, что бы увидеть список установленных версий, вам нужно запустить команду:
После установки, вам нужно выбрать дефолтную версию для вашей системы:
LearnInstall Node.js and NPM on a Mac: How-To Guide
Dave McFarland
writes on October 8, 2014
JavaScript is one of the most popular programming languages in the world. Because it’s built into most web browsers, programmers and web designers can use JavaScript to add interactive features to websites that reach billions of people. But in the past couple of years, JavaScript has started to play a larger role outside of the browser, due in large part to Node.js.
Node.js is a tool for building fast network applications. It’s known as a “JavaScript runtime environment” which simply means it lets you write JavaScript code that can run on your computer free of any web browser. Node.js is used to create fast web servers by companies like Walmart, eBay and Netflix.
But before you can use Node.js or NPM you need to install them — while the NodeJS website includes an installer, there’s a better way to install them on a Mac. In this article, I’ll take you through the process of installing Node.js and NPM on a Mac using Homebrew. In another article, I’ll show you Windows users how to install them on the Windows operating system.
Prerequisites
Before you install Node.js and NPM you’ll first need to have some familiarity with the Mac Terminal application. Terminal lets you dig into the underbelly of the operating system and issue text commands to your computer. You’ll need to use Terminal (or a similar application like iTerm) to not only install Node.js but also to use it and NPM.
Before you can install Node, you’ll need to install two other applications. Fortunately, once you’ve got these on your machine, installing Node takes just a few minutes.
Why Homebrew?
Observant readers will notice in the screenshot above that there’s an installer for NodeJS. You can download it directly from NodeJS.org. I recommend Homebrew over that installer for a few reasons:
Installation
Installing Node.js and NPM is pretty straightforward using Homebrew. Homebrew handles downloading, unpacking and installing Node and NPM on your system. The whole process (after you have XCode and Homebrew installed) should only take you a few minutes.
To make sure you have Node and NPM installed, run two simple commands to see what version of each is installed:
Check and Update Your Node and NPM Versions with Homebrew
New versions of Node and NPM come out frequently. You can use Homebrew to update the software it installs.
How to Uninstall Node and NPM
You can use Homebrew to uninstall packages that it installed: brew uninstall node
With Node.js and NPM installed you’ll soon be able to take advantage of the huge world of NPM modules that can help with a wide variety of tasks both on the web server and on your desktop (or laptop) machine. The NPM site lists all of the official Node packages making it easy to make the choice. Have fun and check out my current courses at Treehouse.
Learn with Treehouse
What sets Treehouse apart is their dedication to helping you find your perfect job or develop your own business. – SwitchUp.org
Follow us on Twitter, Instagram, and Facebook for our favorite tips, and to share how your learning is going. We’ll see you there!
If you liked reading this article, you should also look at these two:
100 Responses to “Install Node.js and NPM on a Mac: How-To Guide”
So how is it npm works in one project but not another? And if there is a way to install it per project, how is that done?
You need node.js and npm installed on your home machine, too. “Command not found” means it’s not installed. Follow the instructions above, and you’ll have everything you need to destroy your free time with work stuff.
You need to install NodeJS globally. NPM comes with it and that is how you’re going to be building your project dependancies. Now if you don’t want to install all those packages that your project requires, then you’re going to want to have your JSON file call them up as devDependancies. Take a look at the link below, it might explain it better than I can.