- Installing Node.js® and NPM on Mac
- What’s Node.js® and NPM?
- Prerequisites
- Installation Overview
- Installation Steps
- Test it!
- How to Update Node and NPM
- How to Uninstall Node and NPM
- Как установить Node.js и NPM в Mac OS
- Как установить Node.js и NPM через Homebrew
- Как установить Node.js и NPM через установщик
- Как узнать, установлены ли NPM и Node.js на Mac
- Как проверить работу Node.js
- Установка node.js на Mac OS
- Что такое Node.js
- Установка Node.js
- Пакеты Node.js
- Создание пакета package.json
- Читайте также
- How to Install Node.js and NPM on Mac OS
- How to Install Node.js and npm on Mac OS with Homebrew
- Installing Node.js & NPM on the Mac with a package installer
- How to Check if NPM and Node.js are installed on a Mac
- How to Test that Node.js is Working
- Related
- Enjoy this tip? Subscribe to our newsletter!
- Thank you!
- Related articles:
- 16 Comments
Installing Node.js® and NPM on Mac
What’s Node.js® and NPM?
Node.js® is a JavaScript-based environment which you can use to create web-servers and networked applications. You can also use it to perform helpful tasks on your computer such as concatenating and minifying JavaScript files and compiling Sass files into CSS.
NPM is a “package manager” that makes installing Node “packages” fast and easy. A package, also called a module, is just a code library that extends Node by adding useful features. For example, the “request” module simplifies the process of making HTTP requests so you can easily get web resources from other sites.
NPM is installed when you install Node.js®
Although there is a Mac installer program on the Node website, we recommend using Homebrew to install and update Node.
Prerequisites
- You should have some familiarity with the Mac Terminal application since you’ll need to use it to install and test Node and NPM. You’ll also need the Terminal to use Node.js and NPM. The Terminal application is located in the Utilities folder in the Applications folder.
- Dependencies. Although you can install Node in other ways, we recommend using Homebrew. Homebrew lets you avoid possible security problems associated with using the sudo command to install software like Node and Node modules.
- Install Homebrew. Follow the steps on the How to Install Homebrew on a Mac instruction guide to install Homebrew.
Installation Overview
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 Homebrew installed) should only take you a few minutes.
Installation Steps
- Open the Terminal app and type brew update . This updates Homebrew with a list of the latest version of Node.
- **Type brew install node .
- Sit back and wait. Homebrew has to download some files and install them. But that’s it.
Test it!
Make sure you have Node and NPM installed by running simple commands to see what version of each is installed:
- Test Node. To see if Node is installed, type node -v in Terminal. This should print the version number so you’ll see something like this v0.10.31 .
- Test NPM. To see if NPM is installed, type npm -v in Terminal. This should print the version number so you’ll see something like this 1.4.27
How to Update Node and NPM
New versions of Node and NPM come out frequently. You can use Homebrew to update the software it installs.
- Make sure Homebrew has the latest version of the Node package. In Terminal type brew update
- Upgrade Node: brew upgrade node
How to Uninstall Node and NPM
You can use Homebrew to uninstall packages that it installed:
Источник
Как установить Node.js и NPM в Mac OS
Node JS – популярная платформа Javascript, которая широко используется разработчиками, а npm – это аккомпанирующий её менеджер пакетов. Когда вы установите Node.js, npm установится автоматически. Соответственно, если вам нужен npm, придётся установить и NodeJS.
Есть несколько способов установить Node.js и NPM на Mac, включая использование установщика и использование Homebrew. В данной статье мы расскажем об обоих способах, которые должны работать во всех современных версиях MacOS.
Как установить Node.js и NPM через Homebrew
Самый простой способ установить node.js и npm – через утилиту командной строки Homebrew. Естественно, для этого у вас должен быть установлен менеджер пакетов Homebrew. Кроме того, не помешает обновить программу перед тем, как приступать к инструкции. Выполните следующую команду:
После этого в программе Terminal выполните такую команду, чтобы установить сразу Node.js и npm:
Данный способ самый простой из всех, и с его помощью node.js и npm легко обновлять. Кроме того, удалить их будет так же просто.
Как установить Node.js и NPM через установщик
Если вы по какой-то причине не хотите использовать Homebrew, можете использовать установщик с сайта nodejs.org:
Запустите установщик, как любую другую программу на Mac.
Как узнать, установлены ли NPM и Node.js на Mac
Вы можете узнать, установлены ли node.js и npm на вашем компьютере, использовав следующие команды:
Как проверить работу Node.js
Когда программная платформа node.js будет установлена, вы можете проверить его работу, создав простой сервер. Создайте файл с названием «app.js» со следующим кодом:
Сохраните файл app.js, а затем запустите сервер следующей командой:
Затем откройте браузер и перейдите по этой ссылке:
Вы должны увидеть сообщение « Hello from Node.js».
Это самый простой веб-сервер, созданный с помощью node.js. Вы также можете установить программу Grunt CLI для тестирования node и npm с помощью такой команды:
После этого запустите в командной строке «grunt».
Выше мы рассказали о самых простых способах установить NodeJS и npm на Mac. Надеемся, они вам помогут.
Источник
Установка 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 заходим в любую директорию, где нужно создать такой файл и запускаем в консоле команду:
Читайте также
Кстати, на сайте нет рекламы. У сайта нет цели самоокупаться, но если вам пригодилась информация можете задонатить мне на чашечку кофе в макдаке. Лайкнуть страницу или просто поблагодарить. Карма вам зачтется.
Источник
How to Install Node.js and NPM on Mac OS
Node JS is the popular Javascript runtime environment that is widely used by many developers, and npm is the accompany package manager for the Node.js environment and Javascript. When you install Node.js, you will find npm is installed as well, thus if you want npm you need to install NodeJS.
There are several ways to install Node.js and NPM on the Mac, including using a prebuilt packaged installer, or by using Homebrew. This tutorial will cover both, and either approach should work find on any modern version of MacOS system software.
How to Install Node.js and npm on Mac OS with Homebrew
The easiest way to install node.js and npm is with the Homebrew package manager, which means first you will need to install Homebrew on the Mac first if you have not done so already. It’s always a good idea to update Homebrew before installing a Homebrew package, so run the following command to do that:
Assuming you already have Homebrew on the Mac, then you can run the following command into the Terminal application to install both Node.js and npm:
brew install node
Installing NodeJS / NPM via Homebrew is arguably easier than using any other method, and it also makes it simple to keep node.js and npm updated. It also has the added benefit of making it relatively simple to uninstall down the road if you decide you no longer need it.
Installing Node.js & NPM on the Mac with a package installer
If you don’t want to use Homebrew for whatever reason, the other next easiest option is to use a the prebuilt installer from nodejs.org:
You can run the installer like any other installation package on the Mac.
How to Check if NPM and Node.js are installed on a Mac
After you have installed node.js with npm, you can confirm that the two are installed by issuing either command with a -v flag to check the version:
How to Test that Node.js is Working
Once the node.js package is installed on the Mac you can test it’s working by starting a simple web server. Create a file named “app.js” that contains the following code syntax:
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 from NodeJS\n’);
>);
Save that app.js file to the current directory, then you can start the web server with the following command:
Then launch a web browser (your default or otherwise) and go to the following URL:
You should see a message stating “Hello from Node.js”.
That simple node.js web server is sort of like the python instant web server except of course it’s using node rather than python. Speaking of Python, if you’re installing Node.js and NPM you may also be interested in instilling the updated Python 3 on a Mac too.
You can also install and use Grunt CLI task runner to test node and npm, which can be installed through npm:
npm install -g grunt-cli
You can then run ‘grunt’ from the command line.
That should just about cover the basics of installing NodeJS and npm on a Mac. If you have any other tips, tricks, suggestions, or advice, feel free to share them in the comments below.
Related
Enjoy this tip? Subscribe to our newsletter!
Get more of our great Apple tips, tricks, and important news delivered to your inbox with the OSXDaily newsletter.
Thank you!
You have successfully joined our subscriber list.
Related articles:
16 Comments
//Use this for app.js.
//Not sure why the smart quotes are used above.
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 from NodeJS\n’);
>);
server.listen(port, hostname, () => <
console.log(‘Server running at http://$
>);
Here’s how to uninstall a package with NPM too:
npm uninstall NAME
hi, I’m at a loss. Need node and npm for a package we want to run. Macbook air, High Sierra 10.13.6. Installed command line, homebrew, then node and npm using brew. Got good responses from version test:
tigger$ node -v
v10.7.0
Lothlorien:
tigger$ npm -v
6.2.0
But get syntax errors when I try to run the app.js – I did write it in brackets and the code looks clean (I copied and pasted) but I’m getting this:
tigger$ node app.js
/Users/tigger/app.js:1
(function (exports, require, module, __filename, __dirname) < const http = require(‘http’);
^
SyntaxError: Invalid or unexpected token
at new Script (vm.js:74:7)
at createScript (vm.js:246:10)
at Object.runInThisContext (vm.js:298:10)
at Module._compile (internal/modules/cjs/loader.js:657:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:266:19)
Suggestions? Is there something I missed? Please help! Thanks
Looks like a javascript error, it’s probably nothing to do with node but instead something with the Javascript itself, thus check the actual source itself for syntax issues or even formatting/character problems.
If the file is not a plain text document for example, or sometimes copying/pasting from the web, or if you’re on a Mac sometimes the quotations get changed or some characters can be ‘autocorrected’ to different quotation marks etc especially if you used a regular text editor rather than a code editor (plain text always!)
You likely need to get the source for “app.js” again, try to download it from git or somewhere similar to make sure it does not get mangled.
YES! Actually, when I look at the code in this post, the single quotes appear to be smart quotes. So when I copy/pasted and saved as plain text, they still were smart quotes. I simply hand replaced them all with regular single quotes, and it ran like a charm! Thank you for the response, so I took a closer look. (I was using a code editor, Brackets, but it did not point out the issue clearly to me)
@moss and @tig: Thank you for your sharp eagle’s eye. I likewise encountered the script error when I tried to launch the server. Following tig’s suggestion, the server installed and ran just fine after fixing the fancy quotes. 🙂
Thanks for the article, Peter. You’re responses to the comments were my favorite part though!
So now I’ve installed this what can I do with it?
(Except I haven’t installed it because I don’t know what to do with it!)
I am always puzzled by internet comments. It’s as if people read the headline (or not even that) and then jump right to the comments to rant, rave, or opine about what they could have learned had they read the article they commented on.
Stunningly, the very first sentence of this article answers the question posed here by Steve:
“Node JS is the popular Javascript runtime environment that is widely used by many developers, and npm is the accompany package manager for the Node.js environment and Javascript”
Sometimes I think there should be a quiz before allowing internet comments!
Источник