Npm install raspberry pi

Install Node.js and Npm on Raspberry Pi

Introduction: Install Node.js and Npm on Raspberry Pi

You can build many apps using node.js and npm on your raspberry pi and it’s very easy to interact with GPIO or other components connected to your raspberry pi. So if you are like me and like to do it on node.js here a few simple steps to install node and npm.

Step 1: Detect What Version of Node.js You Need

The processor on Raspberry Pi is ARM, but depends on the model there can be ARMv6, ARMv7 or ARMv8. This 3 versions of ARM is supported by Node.js.

So first of all type this in your terminal on raspberry pi to detect the version that you need:

If the response starts with armv6 than that’s the version that you will need. For example for raspberry pi zero W you will need ARMv6

Step 2: Download Node.JS Linux Binaries for ARM

Go to node.js download page and check right click on the version of ARM that you need and choose Copy Link address.

After that in the terminal using wget download the tar.gz file for that version. Just type wget, paste the link copied before and make sure the extension is .tar.gz. If it’s something else change it to this and it should be ok. For example I will need ARMv6 and I will type this in my terminal:

Step 3: Extract the Archive

Using tar that is already installed with the system on your raspberry pi just type this (make sure you change the filename with the file that you have)

Step 4: Copy Node to /usr/local

Step 5: Check If Everything Is Installed Ok

Check if node and npm are installed correctly. This lines should print the version of node and npm installed.

Now you have node.js installed on your Raspberry Pi and working so you can build something using node

8 People Made This Project!

Did you make this project? Share it with us!

Источник

How to install Node JS and NPM on the Raspberry Pi

So you want to use your Raspberry Pi as a NodeJS server? You are at the right place! In this short tutorial we will go through how to install NodeJS and the Node Package Manager (NPM) on the Raspberry Pi.

Step 1: Update & Upgrade your Pi

To prevent any issues with compatibility, always update the dependencies list on the Raspberry Pi and upgrade the libraries on the Pi before installing new libraries. Run the following commands in the terminal.

sudo apt-get update

This command updates the list of packages that can be installed, and checks if currently installed packages have any new updates. After the update of the list is completed, run the following command to install the updates.

sudo apt-get upgrade

It takes quite some time for the Raspberry Pi to be updated depending on which version of Raspbian you are using. Once that’s done we can move on to the next step!

Step 2: Determine which version of Node you need

The Raspberry Pi runs off the ARM architecture and as of the writing of this article, NodeJS releases compiled Linux binaries for ARMv6, ARMv7 and ARMv8 architecture boards.

To find out which architecture your Raspberry Pi is running on, run the following command in the terminal

For example, if we run the above command on the Raspberry Pi Zero W, we get the following output.

For easy reference, we have compiled a list of common Raspberry Pi boards and their architectures. (Note that your board might have a different architecture even though the board name is the same as our table as within the same model number there are different revisions, safest bet is to run the above command)

Board Name Architecture Version
Raspberry Pi 4B ARMv8
Raspberry Pi 3 /3B+ ARMv7
Raspberry Pi 2B v1.2 ARMv7
Raspberry Pi 2B ARMv6
Raspberry Pi Zero /Zero W ARMv6

Step 3: Download the NodeJS Binaries

Visit the NodeJS downloads page and copy the link to the version that you need.

If you cannot find your version’s download link, it might be that it has not been released for the latest version of NodeJS. For example, the Raspberry Pi Zero W runs on ARMv6 architecture, but the link is not showing in our screenshot. This is because the ARMv6 binary for NodeJS v12 has not been released. To find the binary for the previous version of NodeJS, visit the previous releases page. Usually the version that is one major revision preceding the LTS version should have binaries for all the architectures. In our case, that is NodeJS v11. So on the page, we will look for «Node.js v11.X.X» where X is the latest revision of that major revision.

Once you have the link for the binaries, you can go ahead and download the archive onto your Raspberry Pi using wget.

wget [COPIED LINK HERE]

Replace [COPIED LINK HERE] with the link you copied from the downloads page. In our case, we needed the binaries for the ARMv6 architecture of the Raspberry Pi Zero W. At the time of writing, the latest NodeJS binary for ARMv6 was v11.15.0. Hence, our command to download was the following.

The download may take some time depending on your internet connection. If the download fails you can always download the file on your laptop and transfer the file to your Raspberry Pi with a removable drive (assuming you are not running it headless)

Step 4: Extract the file

Once the file in on your Raspberry Pi, you need to extract it. To do so, we can use the built in command «tar»

tar -xzf node-vXX.XX.X-linux-armvXl.tar.gz

Change X to your downloaded file name. In our example, we would use the following command

tar -xzf node-v11.15.0-linux-armv6l.tar.gz

The «-xzf» flag is actually 3 flags combined into one, it could also be written as «-x -z -f». The «-x» flag is to tell the program to «extract». The «-z» flag is to tell the program to use «gunzip» for the extraction as the file is an archive ending in «.gz». And finally the «-f» flag simply just means «perform operation on this file».

Step 5: Copy the files to a directory in PATH

To be able to run node from any directory, we need to copy the files extracted to a folder that is in PATH. One possibility is to copy it to the «/usr/local» folder.

As before, change the X to whatever version you need. In our case, we used the following

To copy the files, we use the cp command. The «-R» flag is to signify to the program to copy all the files recursively, i.e include all files within folders. «*» just means to copy everything in the folder.

sudo cp -R * /usr/local/

Step 6: Check if installation was successful

To check if the installation was successful, simply run the following commands to check the versions of NodeJS and NPM in any directory.

If all works well, the above commands should output the version numbers of NodeJS and NPM.

Well, that’s all you need to do to install NodeJS and NPM on your Raspberry Pi. Hope that this tutorial has helped some of you out there. If you run into any issues, just leave us a comment down below and we will try to help you guys as soon as possible! :)

Источник

Install Node.js 16 and npm on Raspberry Pi

Node.js is an open-source runtime environment that allows to run JavaScript code on the server without a browser. It is based on Chrome’s V8 JavaScript engine. Node.js is commonly used to develop web applications. NPM is a package manager for Node.js that allows to install packages from remote registry.

Node.js 16 is a long-term support (LTS) release. In this release the V8 JavaScript engine has been updated from 8.6 to 9.0. This tutorial shows how to install Node.js 16 and npm on Raspberry Pi.

Install Node.js and npm

Connect to Raspberry Pi via SSH and add NodeSource repository that maintains Node.js 16 binary distributions.

Run command to install Node.js:

Note that, we don’t need to install npm separately, it comes bundled with Node.js. After the installation is complete, check Node.js and npm versions:

Testing Node.js

Navigate to your home directory and create a new main.js file:

When a file is opened, add the following code:

Now use the node command to test a program:

Uninstall Node.js and npm

We can remove any package with a name that starts with nodejs and anything related to it by running the following command:

We can also remove NodeSource repository and signing key:

Install older versions

Node.js 14 is older LTS version that is still supported. It can be installed by adding the following NodeSource repository:

The 3 Comments Found

thank you so much for this great tutorial, it was very helpful.

Источник

Как установить Node.js и npm на Raspberry Pi

Node.js — это кроссплатформенная среда выполнения JavaScript с открытым исходным кодом, построенная на движке JavaScript Chrome, которая позволяет выполнять код JavaScript на стороне сервера. Он в основном используется для создания серверных приложений, но также очень популярен как полнофункциональное и интерфейсное решение. npm — это менеджер пакетов по умолчанию для Node.js и крупнейшего в мире реестра программного обеспечения.

В этом руководстве мы объясним, как установить Node.js и npm на Raspberry Pi. Мы предполагаем, что на Raspberry Pi установлен Raspbian .

Установите Node.js и npm из репозитория NodeSource

NodeSource — это компания, специализирующаяся на предоставлении поддержки узлов корпоративного уровня. NodeSource поддерживает репозиторий APT, содержащий последние версии Node.js.

Включите репозиторий NodeSource, выполнив следующую команду в своем терминале:

После включения репозитория установите Node.js и npm, набрав:

Чтобы проверить установку, выполните следующую команду, которая распечатает версию Node.js:

Вот и все. Вы успешно установили Node.js и npm на свою плату Raspberry Pi.

Установите Node.js и NPM с помощью NVM

NVM (Node Version Manager) — это сценарий bash, который позволяет устанавливать и управлять несколькими версиями Node.js. Используйте этот метод, если вам нужно установить конкретную версию Node.js или если вам нужно установить более одной версии Node.js на Raspberry Pi.

Чтобы установить nvm, выполните следующую команду curl, которая загрузит и запустит сценарий установки nvm:

Сценарий установки клонирует репозиторий nvm из Github в каталог

/.nvm и добавит путь nvm в ваш профиль Bash.

Как говорится в выходных данных, вы можете либо открыть новый сеанс оболочки, либо запустить те команды, которые добавят путь nvm к вашему текущему сеансу. Делай то, что тебе легче.

Чтобы убедиться, что nvm установлен правильно, введите:

Теперь вы можете установить последнюю доступную версию Node.js, запустив:

Чтобы лучше объяснить, как работает nvm, мы установим еще две версии: последнюю версию LTS и версию 8.9.4.

После установки обеих версий перечислите экземпляры Node.js, набрав:

В выходных данных выше запись со стрелкой справа (-> v8.9.4) — это версия, используемая в текущем сеансе оболочки, а версия по умолчанию установлена на v12.3.1 .

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

Чтобы изменить v10.16.0 активную версию на v10.16.0 используйте следующую команду:

и проверьте это, набрав:

Если вы хотите установить версию 10.16.0 в качестве типа версии Node.js по умолчанию:

Установить инструменты разработки

Чтобы иметь возможность компилировать и устанавливать собственные надстройки из реестра npm, вам необходимо установить инструменты разработки:

Удалите Node.js

Если по каким-то причинам вы хотите удалить пакет Node.js, вы можете использовать следующую команду:

Выводы

Мы показали вам два разных способа установки Node.js и npm на вашу плату Raspberry Pi. Выбор метода зависит от ваших требований и предпочтений. Несмотря на то, что установка упакованной версии из репозитория NodeSource проще, метод nvm дает вам больше гибкости для добавления и удаления различных версий Node.js для каждого пользователя.

Теперь, когда вы установили Node.js в свою систему Raspberry Pi, вы можете приступить к разработке своего приложения.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии ниже.

Источник

stonehippo / nodejs_raspberry_pi.md

Setting Up Node.js On Raspberry Pi

There are several ways that you can set up Node.js on a Raspberry Pi when running Raspbian/Rapberry Pi OS. Depending on your needs, the version of the RPi that you’re using, and how you like to manage installs, you have a lot of options.

Node.js from source

Do not do this if you can avoid it, it’s super slow. If you insist on doing it and have the time, you can start at https://nodejs.org. But really, don’t do this.

If you have tons of time on your hands, don’t need Node anytime soon, and insist on building from source for some reason, here’s a guide you can try out that covers building Node.js on an ARMv6 Raspberry Pi.

Install with apt

This method is pretty easy:

This works and is a reasonably quick install, but the version of Node.js is likely to be pretty old, since the official repo doesn’t get updated often.

Fortunately, there’s another way…

Install with apt , using NodeSource Binary Distribution

This is probably your best bet if you only work with one version of Node and still want the convenience of using apt . See the install instructions at Nodesource binary distribution, but here’s the basics:

This method lets you pick a modern version of Node.js, and still use apt , so you can get updates pretty easily. Unfortunately, NodeSource only build for armv7/armv8, so this won’t work for Raspberry Pis that use armv6, like Pi 1 and the Pi Zero/Zero W. For those, see the next choice down.

Install a binary from Nodejs.org

You can download and install binaries of Node.js from https://nodejs.org. This method works for all Raspberry Pi models, as long as the official distribution keeps building for armv6.

Note: it looks like official builds for Node on Linux armv6 stopped with the v12.x releases. The last version to get official builds for this platform was v11.x, which is now retired. I recommend sticking with the v10.X/LTS Dubnium releases. At least that version will get support —including security updates— through April 2021. See below for unofficial builds, which will keep your Node.js updated, patched, and supported, but avoids you having to build it yourself.

The good news: you can still get up-to-date armv6 builds from the Unoffical Builds project, including the lastest v14.X LTS versions: https://unofficial-builds.nodejs.org/

Here’s how that works:

I got the lowdown on that from https://github.com/nebrius/raspi-io/wiki/Getting-a-Raspberry-Pi-ready-for-NodeBots. The downside of the above is that it doesn’t put the /usr/local/node/bin directory on your path, so any binary commands that get installed when you do something like npm i -g cli-providing-package will require using the full path.

Another way to install the binary

An alternative method is described here: https://github.com/nodejs/help/wiki/Installation. You might prefer setting up Node this way, since it makes it slightly easier to install mutiple versions (as it puts each version of Node in a subdirectory of /usr/local/lib/nodejs and adds variables to .profile that can be used to switch the versions. This is the method I use on one of my older Pis, and I find that it makes upgrading fairly easy (though far more time-consuming that using nvm or apt ).

NOTE: if you install with this method, you may find that the node , npm , npx or any other binary commands installed via a global node module do not work correctly with sudo . This is because the default sudoers config uses a safe reset for the path. You can override this by setting the path explicitly, like this:

You can also choose to create symlinks so they’ll appear in your path:

I choose to do this, but it means I have to update my symlinks on installation of a new version of Node.

Install with nvm

NVM is a great tool for installing and managing multiple versions of Node.js. I’m not going into detail here (using the installer script and the tools is already well documented), but this is my goto choice, since it allows for simple upgrades and multiple versions.

A quick summary:

  1. Install nvm with the install script
  1. Install a version of Node

Источник