Bazaprogram.ru

Новости из мира ПК
1 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Raspberry pi javascript

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

Главное меню » Информация » Как установить Node.js и npm на Raspberry Pi

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

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

NodeSource – компания, ориентированная на предоставление поддержки Node корпоративного уровня. 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, используйте следующую команду:

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

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

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

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

Удалить Node.js

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

Заключение

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

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

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

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Can I program a Raspberry Pi with Node.js?

I want to learn to program Raspberry Pi’s and I’m pretty good with Node.js. I haven’t touched C++ in almost half a decade. I understand that I can load Linux on the Pi, but how do can I do my programming in Node?

If so, how do I handle things like input / output? If I wanted to make a simple device that detected motion and emitted a beep, for example, is this doable via Node.js on the Pi?

4 Answers 4

I think you need some C ported modules to control the hardware, but I don’t know if there is any.

However you can take a look at Tessel which is an embedded development hardware specialized for JavaScript, so it’s possible to run Node.js applications on your Pi to program it.

Like Dave Swersky said in a comment, yes you can, there s a complete tutorial here: http://blog.rueedlinger.ch/2013/03/raspberry-pi-and-nodejs-basic-setup/

I would add it work well, but you ll need to use Leafpad (if GUI) or nano to edit your code, they are good text editor, but no syntax coloration.

EDIT: For thoses who don t want to see the link, here a quick resume of it:

Creating a new directory for node:

Get the package for Raspbian: (vX.XX.X is to be replaced by latest one)

Add node.js to the PATH:

Add this before ‘export’

It is a rip off of the basic installation of node.js as explained in the link, I didn t writed it, but tested it successfully on two Raspberry.

For more information about why thoses command, and how to properly configure the RPi, go to the link, the real author deserve the credit.

Читать еще:  Как восстановить свою электронную почту на яндексе

EDIT 3 (Inserted before EDIT2 since more related to the question)

For the hardware io with the RPi, you can use the popular socket.io package, or some speciallized module as pi-gpio.

EDIT 2: For nano syntax coloration, copy this in a file named js.nanorc, at

/ for this example Then use this command:

To create a user nano config file and edit it.

Read all option and uncomment those you want, I reccommend to activate:

So you have auto indent, and tabs are made of 4spaces, and by typing alt + P, you see all whitespace replaced by ° (only visual, they aren t replaced in the file)

Then, at the end of the file, type

So you now have coloration for javascript too.

Haven’t used it but perhaps this is what you need: https://npmjs.org/package/pi-gpio

On Linux systems, you can do a lot of fun stuff just by interacting with the files on the procfs, sysfs and configfs filesystems, mounted at /proc , /sys and /sys/kernel/config mountpoints, respectively.

These allow you to observe your system’s status and configuration and in many cases also provide mechanisms to alter that configuration by writing specific data to files. No C/C++ native addons required — the standard fs module will be quite enough.

As an example, take a look at the ledctl library that allows you to control your LEDs simply by reading and writing data to the LEDs’ configuration endpoints on the sysfs mountpoint (Disclaimer: I am the author of the module).

If you would like to interact with your custom devices using the GPIO pins available on Raspberry PI, there are plenty of native addons for Node.js that provide a nice JavaScript API to send and receive signals on particular pins.

So, to create a device that detects a motion and emits a beep, you connect the motion detector and beeper to the GPIO (most likely), take control of the pins using one of your chosen GPIO modules and start listening for incoming signals. When you receive a signal, you emit another signal to the beeper.

Raspberry Pi GPIO Input/Output in Javascript

One of the first hardware hacking examples a new RPi owner is encouraged to try out is turning on an LED via the RPi’s GPIO interface. The standard examples use the Python programming language, but its also possible to do everything you need to do on the RPi in Javascript.

The Raspberry Pi GPIO

The Raspberry Pi provides Input/Outport ports intended to control or monitor other devices and subsystem modules. These GPIO (general purpose I/O) signals on the 2×13 header pins on the RPi “motherboad” include SPI, I2C, serial UART, 3V3 and 5V power. These header pins need to be treated with care to avoid miswiring that could damage your RPi – a short-circuit will send you straight back to the shop for a new RPi. Although there’s also a 5v power signal available on one pin, take note that the I/O pins use a 3V3 logic level (3.3 volts) and are not tolerant of 5V levels, such as you might find on the 5V Arduino boards.

Most of the Raspberry Pi header pins are given the names of the pins of the Broadcom GPIO chip used (BCM2835). There isn’t even a logical relationship between the physical layout of the Raspberry Pi pin header and the GPIO chip’s pinout.

Setting up your Javascript environment – Installing NodeJS

Javascript was originally designed to run within a browser. To run Javascript applications from the command line, you will need to install Node on your Raspberry Pi. Follow the instructions in my previous how-to blog post here.

Comparison of NodeJS GPIO access packages

A number of Node library packages have been developed to control the RPi’s GPIO. Lets take a look at some of them. All these packages are offered under MIT licence.

pi-gpio

A simple node.js-based GPIO helper for the Raspberry Pi.

pi-gpio functions use the physical pin layout on the Raspberry PI header, not the Raspberry Pi or Broadcom GPIO I/O port numbers. That means you can physically connect a peripheral to a RPi header pin and control that pin directly by passing the pin number to the pi-gpio I/O function, without concerning yourself with what the GPIO port designation is for that pin.

Читать еще:  Как восстановить контрольный вопрос на яндекс почте

rpi-gpio

rpi-gpio has two key differences to the pi-gpio package:

  1. pi-gpio functions use the Raspberry Pi GPIO I/O port numbers rather than the physical pin numbers. That means if you physically connect a peripheral to the RPi header pin 11, you need to address it by its GPIO port designation 17. See here for the complete up-to-date guide to GPIO port to header pin mappings on the Raspberry Pi .
  2. All of the I/O functions of the rpi-gpio package are asynchronous, so where necessary – for example in reading the value of a pin – a callback must be provided. This package is thus more closely aligned with the asynchronous nature of the Node platform.

onoff

onoff is a package providing both synchonous and asynchronous GPIO I/O functions. Like rpi-gpio, it uses the GPIO port numbers as I/O function arguments.

In addition, onoff also adds interrupt detection, so that your callback function can be triggered automatically when the value of a GPIO port changes; avoiding the CPU load of polling it.

onoff provides a constructor function called Gpio which can be used to make Gpio objects corresponding to GPIO devices.

How to handle the GPIO super-user privilege restriction

The Raspberry Pi’s GPIO pins require you to have root privileges to access them. That means any program you write that access the GPIO you’ll have to start as root user or using sudo. That’s totally unsafe, as your program then has carte blanche over your RPi and a bug in your program can cause carnage. To get around this problem, you can use the useful gpio-admin tool.

Do the following on your raspberry pi:

After this, you will need to logout and log back in.

Installing the Library

We can install any of the packages using the Node Package Manager npm. We’re going to install pi-gpio

cd back to your project directory and use npm to install pi-gpio in your project.

Hardware

Using a breadboard and connector wires, hook up the header pin 16 (GPIO port 23) to an LED with an appropriately-sized resistor in series.

The value you select for R1 will depend on the current required by the LED (check the datasheet that came with your LED).

We also need to know from that datasheet the forward voltage required by the LED to light, typically around 2V-3.5V.

And we already know the output voltage of the RPi GPIO is 3.3V.

NB: the Raspberry Pi revision 1 and revision 2 hardware have slightly different pin layouts. The most reliable source of information on the RPi GPIO pin layout for your RPi is available on elinux.org here .

Using the Library

Lets build a test application to try out the pi-gpio functions. Using the nano editor, create a new source file called my_gpio_test.js

First we have to tell Node that it needs to load the GPIO package we installed.

We’re going to blink the LED, so lets define some variables

Open a pin in output mode

Blink the LED attached to this pin on and off every 100mS

Let the blinking run for 10 seconds, then close port and exit

Running a Test

Unless you have installed and run gpio-admin (see above), make sure you are running as root or with sudo, else the Raspberry Pi will not let you output to the GPIO.

You should see your LED blink for 10 seconds then see the program terminate naturally.

Raspberry pi javascript

What is the best way to install Node.js on a Raspberry Pi 3?
Is it the same as on a 2, if so what is the best way?
If not, what do I do differently?

Now this maybe a very basic question, but since this is my first experience with a Pi and a Linux OS, I want to make sure I get it right.

Thank you,
Stuart

Re: How to install Node.js on Raspberry Pi 3?

However, I noticed that they picked the armv6. Doesn’t the rPi 3 have armv8 instruction set. Would the armv7 be ‘faster’ than the armv6 that the above tutorial recommend?

This post (viewtopic.php?f=63&t=99963) and reading through the full benchmarks; it seems that perhaps raspbian is/isn’t fully optimized for armv7? Or is it now?

Читать еще:  Java nio channels closedchannelexception

Re: How to install Node.js on Raspberry Pi 3?

Re: How to install Node.js on Raspberry Pi 3?

Raspbian has node installed, but it’s quite old.

To get to a more recent version:

Re: How to install Node.js on Raspberry Pi 3?

It’s better to not install NodeJS directly, but to use NVM for that. This way, switching NodeJS versions is very simple.

Please see my Github repository on how to do that: https://github.com/elgervb/raspberrypi/ . /nodejs.sh

Good luck with it

Re: How to install Node.js on Raspberry Pi 3?

. and no it doesn’t install Node v4.2.6 (post below). It installs the Latest version of Node.

Re: How to install Node.js on Raspberry Pi 3?

Re: How to install Node.js on Raspberry Pi 3?

Re: How to install Node.js on Raspberry Pi 3?

Re: How to install Node.js on Raspberry Pi 3?

Re: How to install Node.js on Raspberry Pi 3?

Re: How to install Node.js on Raspberry Pi 3?

Re: How to install Node.js on Raspberry Pi 3?

Re: How to install Node.js on Raspberry Pi 3?

Re: How to install Node.js on Raspberry Pi 3?

Re: How to install Node.js on Raspberry Pi 3?

so on a new system ( with running NODE-RED )
better use this WAY-A from viewtopic.php?p=1106738#p1106738 because it not makes problems.
and i just confirm by install also v7.8 this way ( over a v7.4):
node -v v7.8.0
npm -v 4.2.0

and node-red say its using node v7.8.0

Re: How to install Node.js on Raspberry Pi 3?

I’ve done that way in raspbian stretch but if I type ‘node’ or ‘npm’ obtained the old versions. I had to ‘apt remove node’ in order to use the new npm version

Re: How to install Node.js on Raspberry Pi 3?

Doing a build of FreePBX starting from a fresh Raspbian Stretch Lite image and installing the latest node.js using:

Re: How to install Node.js on Raspberry Pi 3?

And here I’ve used the https://deb.nodesource.com/node_6.x version, not the 7.x or 8.x . maybe that’s why.

Re: How to install Node.js on Raspberry Pi 3?

Re: How to install Node.js on Raspberry Pi 3?

But its not recognized:

Re: How to install Node.js on Raspberry Pi 3?

But its not recognized:

Re: How to install Node.js on Raspberry Pi 3?

. and no it doesn’t install Node v4.2.6 (post below). It installs the Latest version of Node.

Re: How to install Node.js on Raspberry Pi 3?

Please note that you will not be able to properly debug node.js applications if you do not have the aarch64 build of debain buster installed on the Raspberry PI 3 Model B (not B+) or the Fedora aarch64 release for Raspberry Pi.

You will receive the error in node when attaching the debugger, for IDEs like JetBrains that have these features, on debain stretch:

To fix this, you’ll need:

> A raspberry Pi 3 Model B (Not B+) that incorrectly reports itself as arm7l in Debain stretch (it runs in arm7l 32-bit mode, or armv8 64-bit mode, was recently brought to light mid-2018 after some research on the Cortex A53.
> an aarch64 supported OS, and an arm64 build of node.

The debain buster image:

SDCard image builds fine in Ubuntu 18.04 Bionic VM. (its a lot of work. )
> You will have to fix up the root account, setup sudo, a user, and fix bash.

Quick node install once you have a proper setup:

Re: How to install Node.js on Raspberry Pi 3?

Will not only install the latest version of node, but it will also track future npm global modules that you install. I’ve had to switch versions of node several times for different testing, and it can become a huge pain to not have the global modules that i use regularly when i switch versions. So rather than simply install node (whatever version). Install the node-install utility that comes with: https://github.com/audstanley/NodeJs-Raspberry-Pi

It might save you a lot of headache down the road. and there is «version selecting» that prompts you which comes in handy.
Read the docs, and you’ll see the options.

Also, remember that friends don’t let friends pipe to bash. So read the source code.

Ссылка на основную публикацию
Adblock
detector