NodeJS

Contents
Introduction
Install
Quick Start
Create File
Download Image from Web
Common Errors
Related Articles

Introduction

Node or Node.js is a software platform based on the V8 engine (broadcasting JavaScript into machine code), which turns JavaScript from a highly specialized language into a general-purpose language.

Node.js adds the ability for JavaScript to interact with devices I/O via your API , written in C++ , connect other external libraries written in different languages, providing calls to them from JavaScript code.

Node.js is used primarily on the server, acting as a web server. You can read the installation instructions for virtual hosting here .

It is also possible to develop on Node.js and desktop windowing applications (using NW.js, AppJS or Electron for Linux , Windows and macOS) and even program microcontrollers (for example, tessel, low.js and espruino).

At the core of Node.js is event-oriented and asynchronous (or reactive) programming with non-blocking input/output.

Installation

Download Node js from the official website nodejs.org

Choosing the LTS version (Recommended for most users)

The .msi file should load, for example node-v10.16.3-x64.msi

Install and then check the version with the command

$ node -v

v10.16.3

Install on Linux

On Ubuntu Debian etc.

sudo apt install nodejs

On CentOS , Rocky , Red Hat, Fedora etc.

sudo yum install nodejs

Install and then check the version with the command

$ node -v

v10.21.0

Installing the latest version of node js

There may be a fairly old version of nodejs in the default repository. It depends on the distribution Linux.

Fedora is likely to have a new version.

And in a stable Ubuntu old and, for example, for work rfbrowser she doesn't fit.

You can install the desired version in the following way

sudo apt -y install curl gcc g++ make
curl -sL https://deb.nodesource.com/setup_16.x -o nodesource_setup.sh
sudo bash nodesource_setup.sh
sudo apt -y install nodejs
node -v

v16.14.0

If you don't need the 16th version, just replace setup_16.x with the one you need

During installation, there will be something like this log

## Installing the NodeSource Node.js 16.x repo... ## Populating apt-get cache... + apt-get update Hit:1 http://fi.archive.ubuntu.com/ubuntu jammy InRelease Get:2 http://fi.archive.ubuntu.com/ubuntu jammy-updates InRelease [109 kB] Get:3 http://fi.archive.ubuntu.com/ubuntu jammy-backports InRelease [99.8 kB] Get:4 http://fi.archive.ubuntu.com/ubuntu jammy-security InRelease [110 kB] Get:5 http://fi.archive.ubuntu.com/ubuntu jammy-updates/main amd64 Packages [221 kB] Get:6 http://fi.archive.ubuntu.com/ubuntu jammy-updates/universe amd64 Packages [102 kB] Fetched 644 kB in 0s (1,614 kB/s) Reading package lists... Done ## Confirming "jammy" is supported... + curl -sLf -o /dev/null 'https://deb.nodesource.com/node_16.x/dists/jammy/Release' ## Adding the NodeSource signing key to your keyring... + curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | gpg --dearmor | tee /usr/share/keyrings/nodesource.gpg >/dev/null ## Creating apt sources list file for the NodeSource Node.js 16.x repo... + echo 'deb [signed-by=/usr/share/keyrings/nodesource.gpg] https://deb.nodesource.com/node_16.x jammy main' > /etc/apt/sources.list.d/nodesource.list + echo 'deb-src [signed-by=/usr/share/keyrings/nodesource.gpg] https://deb.nodesource.com/node_16.x jammy main' >> /etc/apt/sources.list.d/nodesource.list ## Running `apt-get update` for you... + apt-get update Hit:1 http://fi.archive.ubuntu.com/ubuntu jammy InRelease Hit:2 http://fi.archive.ubuntu.com/ubuntu jammy-updates InRelease Hit:3 http://fi.archive.ubuntu.com/ubuntu jammy-backports InRelease Hit:4 http://fi.archive.ubuntu.com/ubuntu jammy-security InRelease Get:5 https://deb.nodesource.com/node_16.x jammy InRelease [4,583 B] Get:6 https://deb.nodesource.com/node_16.x jammy/main amd64 Packages [774 B] Fetched 5,357 B in 0s (13.5 kB/s) Reading package lists... Done ## Run `sudo apt-get install -y nodejs` to install Node.js 16.x and npm ## You may also need development tools to build native addons: sudo apt-get install gcc g++ make ## To install the Yarn package manager, run: curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | gpg --dearmor | sudo tee /usr/share/keyrings/yarnkey.gpg >/dev/null echo "deb [signed-by=/usr/share/keyrings/yarnkey.gpg] https://dl.yarnpkg.com/debian stable main" | sudo tee /etc/apt/sources.list.d/yarn.list sudo apt-get update && sudo apt-get install yarn

Getting started

Let's create a folder for a small demonstration of the capabilities of nodejs.

cd go to it and create a test.js file there

$ mkdir test-nodejs
$ cd test-nodejs
$ touch test.js

Оopen the file with a text editor. I usually use Visual Studio Code vi or Sublime Text

I like the first one, but vi is just usually installed everywhere by default.

Creating a file

Let's see how to create files using nodejs.

To a file test.js we will make the following changes

var fs = require('fs');

This line means that the variable1 fs will now call the fs module.

You can read about the capabilities of the fs module in the documentation: nodejs.org/api/fs.html .

In the next part of the code, we will write a function that will create a file and handle possible errors2

fs.writeFile(__dirname + "/index.html", "<h1>HeiHei.ru</h1>", (err)=>{
if (err) throw err;}
console.log("The file has been saved!");}
});

You can read about the fs.WriteFile command in the documentation: nodejs.org/api/fs.html.

Download a picture from the Internet

First of all, we will connect the module https

Create a variable with the same name

var https = require('https');

Let's say we want to download from the site HeiHei.ru a picture of turtles resting in the sun from the park La Paloma .

Create a variable

var myPhotoLocation = 'https://www.heihei.ru/Spain/cities/
benalmadena/img/bmd61.jpg'

And use the https.get method 3

https.get(myPhotoLocation, (res) =>{ res.pipe(fs.createWriteStream(__dirname +"/Turtle.jpg")); })

Do not forget that to use fs, you must first declare a variable.

The whole script:

const fs = require('fs'); const https = require('https'); var myPhotoLocation = 'https://www.heihei.ru/Spain/cities/benalmadena/img/bmd61.jpg'; https.get(myPhotoLocation, (res) => { res.pipe(fs.createWriteStream(__dirname + "/Turtle.jpg")); })

You can read about the https method on the website nodejs.org/api/https.html

var myPhotoLocation = 'https://www.heihei.ru/Spain/cities/
benalmadena/img/bmd61.jpg'

And this is how turtles bask in the sun in La Paloma Park in Benalmadena Spain
Photo: www.HeiHei.ru

Comments

1

Or

const fs = require('fs');

In our example, this will not play a special role. Let's focus on the variant with var

2

If you use an older syntax (if I'm not mistaken, around 7-8 versions) , the code will look like this

fs.writeFile(__dirname + "/index.html", "<h1>HeiHei.ru</h1>", function(error){
if (error) {return console.log(error);}
else {return console.log(" The file has been saved! ");}
});

3

Old syntax

https.get(myPhotoLocation, function(response){ response.pipe(fs.createWriteStream(__dirname +"/Turtle.jpg")); })

Errors

1

Error installing Nodejs

$ npm install Nodejs --save-dev

npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\ao\Desktop\Sites\heihei\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\ao\Desktop\Sites\heihei\package.json'
npm WARN heihei No description
npm WARN heihei No repository field.
npm WARN heihei No README data

npm WARN heihei No license field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ Nodejs@4.0.2
added 314 packages from 217 contributors and audited 6490 packages in 30.037s
found 0 vulnerabilities

events.js:174 throw er; // Unhandled 'error' event
^
CssSyntaxError: postcss-simple-vars: C:\Users\ao\Desktop\Sites\travel-site\app\assets\styles\modules\_large-hero.css:5:2: Undefined variable $aMadeUpVariable2

Can be called, for example, by a nonexistent variable. Let's say you added a color as a variable, but it was not set anywhere.

TypeError [ERR_INVALID_OPT_VALUE_ENCODING]

$ node test.js

internal/fs/utils.js:60 throw new ERR_INVALID_OPT_VALUE_ENCODING
(encoding); ^ TypeError [ERR_INVALID_OPT_VALUE_ENCODING]: The value "<h1>HeiHei.ru</h1>" is invalid for option "encoding" at assertEncoding (internal/fs/utils.js:60:11) at getOptions (internal/fs/utils.js:182:5) at Object.writeFile (fs.js:1164:13) at Object.<anonymous> (C:\Users\ao\Desktop\Sites\heihei\test-nodejs\test.js:3:4) at Module._compile (internal/modules/cjs/loader.js:778:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10) at Module.load (internal/modules/cjs/loader.js:653:32) at tryModuleLoad (internal/modules/cjs/loader.js:593:12) at Function.Module._load (internal/modules/cjs/loader.js:585:3) at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)

Most likely you accidentally added more commas than necessary and node decided that the time after the second comma is not a callback, but something else - so you are setting a parameter to data. Check the team structure.

It should be like this:

fs.writeFile(File name or path to it, data, for example, that you want to add to the file, callback is usually err.

You most likely have:

fs.writeFile(File name or path to it, data, for example, that you want to add to the file, some code unknown to the node, callback is usually err.

You can read about the fs.WriteFile command in the documentation: nodejs.org/api/fs.html.

Related Articles
Gulp
Concat multiple css to one
Send files via ftp with Gulp
Gulp series
Process only changed files with gulp.watch().on('change')
Copy Directory Gulp
Video Tutorials
JavaScript
NodeJS
NPM
Web

Search on this site

Subscribe to @aofeed channel for updates

Visit Channel

@aofeed

Feedbak and Questions in Telegram

@aofeedchat