NodeJS: quick start

Hello! The course starts very soon. “Developer Node.js”in connection with which we held a traditional public lesson. The webinar examined the strengths and weaknesses of Node, and also discussed for what tasks this software platform is best suited, and for which other languages ​​and frameworks should be chosen. And, of course, not without practice. To run examples and programs, you had to install Node.js.

Teacher – Alexander Korzhikov, Dev IT Engineer at ING Group (Netherlands).



A few words about Node.js

Node.js is an asynchronous JavaScript runtime based on concepts such as Event Loop and event-oriented architecture. Node.js platform and NPM standard package manager allow you to create effective applications for various subject areas – from the Web to Machine Learning.

The simplest example of a web server (node server.js):

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 Worldn')
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})

Looking at the code above, the following features of Node.js can be noted:

  1. We can run JavaScript code directly on the server, that is, it is possible to execute JavaScript files using the node command.
  2. The CommonJS-format of modules for loading dependencies and ES Modules is supported, and both formats can be used.
  3. A standard module library is supported, of which HTTP is a part.
  4. The API is based on the asynchronous Callbacks pattern, but Promise is also supported.
  5. ES2015 syntax is supported. By the way, here useful linkwith which you can always see in which version of Node what JS features are supported. If something goes wrong, you can compare and understand what the problem is.

Also don’t miss the small demo (VSCode + Chrome Debug).

A brief excursion into history

The Node.js platform appeared in 2009, the main developer and creator of the project was Ryan Dahl. His main idea was to create a non-blocking I / O (input-output) for the server, and using JavaScript. At that time, such approaches were not very common, and JavaScript was one of the best solutions.

Node.js uses the Chromium engine inside itself, or rather, the part of it that interprets JavaScript – V8. Due to the fact that the interpreter at one time separated into a separate V8 project, it became possible to simply create an ecosystem around it. Strictly speaking, this is exactly what the creator of Node.js Ryan Dahl did. By the way, today there is the Node.js Foundation, an organization that supports the project.

Structure

Firstly, the library is written in C ++ and JavaScript. Project itself lies on github, so if you are curious, you can familiarize yourself with its source code. Delving into his study can be very long)).

Secondly, as already mentioned, it includes V8 (the JavaScript execution platform from Google) and libuv as part of the Event Loop (asynchronous event loop).

Well, of course, there are various modules for working with the operating system that allow you to perform those business tasks that you need.

It is also worth mentioning the main design patterns that are commonly used in Node.js:

  • Callback (it was already mentioned);
  • Observer (simpler event pattern);
  • Module (although it is now organized in the JavaScript language itself, in Node.js it is still relevant);
  • Reactor (pattern of asynchronous interaction with some resources when you do not block the main stream of code). This pattern is familiar to JS developers. For example, if we work in a browser and write a frontend, we do not block all browser work, but simply subscribe to events from the user, and when the event occurs (after a “click”, “enter”, etc.), we execute our code.

By the way, here you are little competitionheld at the webinar)). And move on.

Node Standard Distribution Modules

Do you know which modules are included in the standard Node distribution? That is, we are talking about modules that are already built-in, therefore, they can not be installed. In general, there are about 50 of them, let’s list the main ones. For convenience, we will conditionally divide them into 5 points:

1. Main (for ordinary operations):

  • fs;
  • timers;
  • streams (for work with streams).

2. Utilities:

  • path (for working with paths);
  • util;
  • zlib (archiving and unzipping);
  • crypto (for cryptographic functions).

3. Processes (everything related to multiprocessing and parallelism):

  • child_process (the main module for launching minor modules, provides great opportunities for starting and monitoring processes);
  • cluster (similar to the first, but allows you to parallelize tasks on the cores of your processor);
  • worker_threads (implementation of threads or threads, but it is not completely thread-safe, but why, it is better to read in the documentation).

4. Protocols (all kinds of protocols):

  • http (s);
  • net;
  • dns.

5. System (respectively, system modules, including debugging):

  • os
  • v8;
  • async_hooks;
  • perf_hooks;
  • trace_events

What else to add:

– globals object – analogue of window;
– all JavaScript objects that are available in the browser are also available in Node.js;
– timeouts – almost like in a browser;
– process – representation of the current process;
– console is available.

Callbacks

Callback – a function passed as an argument to the code, which involves executing it at some point in time. By the way, people rarely think that their execution can be synchronous or asynchronous.

const server = http.createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello Worldn')
})
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`)
})

In Node, by default, callback is executed with an “error” and the result is asynchronous:

fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err
console.log(data)
})

And here is what the antipattern looks like – a good example of how to use Callbacks incorrectly. As the saying goes, classic callback hell:

fs.readdir(source, function (err, files) {
if (err) {
console.log('Error finding files: ' + err)
} else {
files.forEach(function (filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function (err, values) {
if (err) {
console.log('Error identifying file size: ' + err)
} else {
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach(function (width, widthIndex) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
if (err) console.log('Error writing file: ' + err)
})
}.bind(this))
}
})
})
}
})

Now let’s see how create a simple web server and give the HTML index as a client response:

const http = require('http')
const server = http.createServer((req, res) => {
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('Hello Worldn')
})

To read the local html file:

const fs = require('fs')
fs.readFile('./index.html', (err, text) => {
console.log(text)
})

Finishing the topic of callbacks, I would like to mention Callback Types. There are callbacks that return only an error if there is an error:

fs.access('/etc/passwd', fs.constants.R_OK, (err) => {
console.log(err ? 'no access!' : 'read')
})

Also now, more and more modules and APIs use Promises out of the box, which is good. Node supports Promises:

util.promisify()
fs.promises.*

Return Type:

http.request('https://example.com', (error, response, body) => {
...
})

Node Q&A

When writing web servers, Express is often used, although there are many other libraries and frameworks that implement similar functionality. Nevertheless, Express is the most popular and stable. You could say this is the standard for writing servers.

import express from "express";
const app = express();
const port = 3000;
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(port, () => {
console.log(`Example app listening
});

Well, now you can try to create a web server with Express generator:

  • using jade, cookie-session;
  • by making a naive login logout.

Or just see how the teacher did it, prepared a ready-made solution on TypeScript.

That’s all. Finally – a couple of useful links:

And see you later on course.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *