ITKarma picture

Good day, friends!

I continue to publish translations of this Node.js tutorial .

Other parts:
Part 1
Part 2
Part 3

The JavaScript V8 Engine


V8 is the name of the JavaScript engine supported by Google Chrome. This is the thing that takes your JavaScript code and executes it in the browser.

In other words, V8 is a JavaScript runtime. DOM and other web APIs are also provided by the browser.

JavaScript engine is browser independent. This is what led to the emergence of Node.js. V8 was chosen as the engine for Node.js in 2009, and with the growing popularity of Node.js, V8 became the basis for a lot of server-side JavaScript.

The ecosystem of Node.js is huge and thanks to V8 we are able to create desktop applications, for example, using Electron.

Other JS engines

Other browsers have their own JavaScript engines:


etc.

All of these engines implement the ECMA ES-262 (ECMAScript) standard , the standard used by JavaScript.

About performance

V8 is written in C++ and continues to evolve. It works on all operating systems.

We will not consider the features of the V8 implementation: you can find them here , they change from time to time, often radically.

V8 is constantly evolving, like other JavaScript engines, to increase the speed of the web and the Node.js ecosystem.

There is a competition for productivity on the web that lasts for many years, and we (as users and developers) get a lot from this competition, because we get faster and more optimized tools every year.

Compilation

JavaScript is usually positioned as an interpreted language, but modern engines do not just interpret JavaScript, they compile it.

This has been happening since 2009 when the SpiderMonkey JavaScript compiler was added in Firefox 3.5.

JavaScript compiles V8 on the fly (just-in-time, JIT, dynamic compilation) to speed it up.

This may seem counterintuitive, but with the advent of Google Maps in 2004, JavaScript evolved from the language in which small blocks of code are written to the language in which full-fledged applications are created, consisting of hundreds and thousands of lines of code running in the browser.

Today, our browser-based applications can work for hours, they are no longer simple tools for solving primitive tasks, such as form validation.

In the modern world, compiling JavaScript makes sense: despite the fact that it takes more time to prepare the code, its performance significantly exceeds the performance of the interpreted code.

Running Node.js scripts using the command line


The standard way to run programs on Node.js is to execute the global command CDMY0CDMY and transfer the name of the executable file.

If the main file of your Node.js application is called CDMY1CDMY, you can call it like this:

node app.js 

When executing the specified command, make sure that you are in the directory with the CDMY2CDMY file.

How to exit Node.js?


There are various ways to stop a Node.js application.

When starting a program through a terminal, you can close it using CDMY3CDMY, however, let's discuss software methods.

Let's start with the most radical, and talk about why it should not be used.

The main (global, kernel module) module CDMY4CDMY contains a convenient method that allows you to programmatically exit the Node.js application: CDMY5CDMY.

When Node.js reaches this line of code, the program execution process ends immediately.

This means that all executed callback functions, sent (incomplete) requests, open access to the file system, writing processes in CDMY6CDMY or CDMY7CDMY - all of them will be hard interrupted.

If this is acceptable for you, you can pass an integer to the CDMY8CDMY method - a signal to complete the code:

process.exit(1) 

By default, the exit code is 0, indicating success. Different exit codes have different meanings, you can use them to ensure the interaction of some programs with others.

You can read more about exit codes here .

You can also assign the corresponding value to the CDMY9CDMY property:

process.exitCode=1 

and after the program finishes, Node.js will return this code.

Program execution will end gently when all processes are completed.

In Node.js, we often start the server:

const express=require('express') const app=express() app.get('/', (req, res) => { res.send('Hi!') }) app.listen(3000, () => console.log('Server ready')) 

This program will never end. If you call CDMY10CDMY, all pending or running requests will be aborted. Is not cool.

In this case, send the CDMY11CDMY signal command and process it using the processor signal handler (CDMY12CDMY does not need to be connected, it is available by default):

const express=require('express') const app=express() app.get('/', (req, res) => { res.send('Hi!') }) const server=app.listen(3000, () => console.log('Server ready')) process.on('SIGTERM', () => { server.close(() => { console.log('Process terminated') }) }) 

What are signals? Signals is a POSIX communication system: sending a notification of an event to a process.

CDMY13CDMY - a signal about the immediate completion of the process, similar to CDMY14CDMY.

CDMY15CDMY - signal about soft termination of the process. This signal can be sent by a process control system such as CDMY16CDMY, CDMY17CDMY, etc.

You can send this signal inside the program through another function:

process.kill(process.id, 'SIGTERM') 

Or from another Node.js program or any other application running on the system, provided that they know the PID of the process that you want to complete.

How to read environment variables in Node.js?


The main module Node.js CDMY18CDMY has the CDMY19CDMY property, which contains all the environment variables set at the start of the process.

Here is an example of accessing the NODE_ENV environment variable set to CDMY20CDMY by default:

process.env.NODE_ENV//development 

Setting a value in production before running the script will tell Node.js that it has a production environment in front of it.

In a similar way, you can access any set environment variable.

How to use Node.js REPL


The CDMY21CDMY command is used to run Node.js scripts:

node script.js 

If we omit the file name, we get into REPL mode:

node 

REPL (Run Evaluate Print Loop) is a code runtime (usually a terminal window) that accepts an expression entered by the user and returns the result of evaluating this expression.

If you enter CDMY22CDMY in the terminal, the following will happen:

> 

The terminal will go into standby mode.

To be more precise, the terminal in this case expects to enter some kind of JavaScript code.

We introduce the following:

> console.log('test') test undefined > 

The first value, CDMY23CDMY, is what we ordered to output to the console, then we get CDMY24CDMY - the value that returned CDMY25CDMY execution

After that we can enter something else.

Using CDMY26CDMY for autocompletion

REPL is interactive.

If you press CDMY27CDMY while writing code, REPL will attempt to complete the writing by choosing from previously defined or predefined variables.

JavaScript objects

Try entering the name of the JavaScript class, for example, CDMY28CDMY, add a period to it, and click CDMY29CDMY.

REPL will show all the properties and methods of this class:

ITKarma picture

Global objects

You can get a list of global objects by entering CDMY30CDMY and clicking CDMY31CDMY:

ITKarma picture

Special Variable _

If you type CDMY32CDMY at the end of the code, the result of the last operation will be displayed.

Commands after the period

REPL contains some special commands starting with a period. Here they are:

  • CDMY33CDMY - shows a list of available commands
  • CDMY34CDMY - enables editing mode for writing multi-line JavaScript code. To execute the code in this mode, press CDMY35CDMY
  • CDMY36CDMY - stops entering multi-line code. Similar to pressing CDMY37CDMY
  • CDMY38CDMY - resets the REPL context to an empty object, deletes all entered code
  • CDMY39CDMY - loads a JavaScript file located in the current (working) directory
  • CDMY40CDMY - saves the REPL session to a file with the specified name
  • CDMY41CDMY - exit REPL. Similar to double-clicking CDMY42CDMY

REPL understands that you enter multi-sided code without calling CDMY43CDMY.

For example, if you started implementing an iteration:

[1, 2, 3].forEach(num => { 

and pressed CDMY44CDMY, REPL will go to a new line with three dots at the beginning, indicating that you can continue working with the code block:

... console.log(num)... }) 

If you enter CDMY45CDMY at the end, the multi-line code dialing mode will stop and the expression will not be executed.

Passing arguments using the command line


When starting a Node.js application, you can pass any number of arguments to it.

Arguments can be autonomous or have a key and a value.

For example:

node app.js joe 

or

node app.js name=joe 

It depends on how you will retrieve the value in the Node.js code.

To retrieve values, the built-in object CDMY46CDMY is used.

The CDMY47CDMY property of this object contains an array of arguments passed through the command line.

The first argument is the full path of the CDMY48CDMY command.

The second is the full path of the executable file.

The arguments we are interested in start from the third position (array index).

You can iterate over the arguments (including the node path and file path) using a loop:

process.argv.forEach((val, index) => { console.log(`${index}: ${val}`) }) 

The arguments passed can be obtained by creating a new array without the first two parameters:

const args=process.argv.slice(2) 

If we have one argument without an index (key):

node app.js joe 

we can get it as follows:

const args=process.argv.slice(2) args[0] 

In this case:

node app.js name=joe 

CDMY49CDMY is CDMY50CDMY, so we need to take it apart. The best way to do this is to use the minimist library, designed to work with arguments:

const args=require('minimist')(process.argv.slice(2)) args['name']//joe 

Here you need to use a double dash before each argument:

node app.js --name=joe 

Outputting results to the command line using Node.js


Standard output via CDMY51CDMY module

Node.js provides a console module , which contains many very useful ways to interact with the command line.

It looks like a browser object CDMY52CDMY.

One of the main methods of this module is CDMY53CDMY, which displays the passed string to the console.

If you pass an object, it will be converted to a string.

We can pass several variables to CDMY54CDMY:

const x='x' const y='y' console.log(x, y) 

and Node.js will output both.

We can also format the string using qualifiers:

For example:

console.log('My %s has %d years', 'cat', 2) 

  • CDMY55CDMY - formats a variable as a string
  • CDMY56CDMY - formats a variable as a number
  • CDMY57CDMY - cast a variable to an integer
  • CDMY58CDMY - formats a variable as an object

For example:

console.log('%o', Number) 

Cleaning the console

CDMY59CDMY clears the console (behavior depends on the console used).

Counting Elements

CDMY60CDMY is a convenient method.

Explore this code:

const x=1 const y=2 const z=3 console.count( 'The value of x is ' + x + ' and has been checked.. how many times?' ) console.count( 'The value of x is ' + x + ' and has been checked.. how many times?' ) console.count( 'The value of y is ' + y + ' and has been checked.. how many times?' ) 

The counter counts the number of line displays and displays this number.

The value of x is 1 and has been checked.. how many times?: 1 The value of x is 1 and has been checked.. how many times?: 2 The value of y is 2 and has been checked.. how many times?: 1 

So you can count the number of apples and oranges:

const oranges=['orange', 'orange'] const apples=['just one apple'] oranges.forEach(fruit => console.count(fruit)) apples.forEach(fruit => console.count(fruit)) 

Display stack trace

There are situations when you need to display the trace of the function stack, for example, in order to answer the question “How did we reach this part of the code?”
You can do this with CDMY61CDMY:

const function2=() => console.trace() const function1=() => function2() function1() 

This will print a stack trace to the console. This is what we will see on the command line if we run the code in Node.js REPL:

Trace at function2 (repl:1:33) at function1 (repl:1:25) at repl:1:1 at ContextifyScript.Script.runInThisContext (vm.js:44:33) at REPLServer.defaultEval (repl.js:239:29) at bound (domain.js:301:14) at REPLServer.runBound [as eval] (domain.js:314:12) at REPLServer.onLine (repl.js:440:10) at emitOne (events.js:120:20) at REPLServer.emit (events.js:210:7) 

Counting code execution time

You can easily calculate how long a function has been running with CDMY62CDMY and CDMY63CDMY:

const doSomething=() => console.log('test') const measureDoingSomething=() => { console.time('doSomething()')//выполняем какие-либо операции и засекаем время их выполнения doSomething() console.timeEnd('doSomething()') } measureDoingSomething() 

stdout and stderr

As we know, console.log is great for outputting messages to the console. This is called standard output or CDMY64CDMY.

CDMY65CDMY displays the CDMY66CDMY stream.

This stream is not output to the console, but is written to the error log.

Styling the output

You can colorize the text output to the console with escape sequences . These sequences are a set of characters that identify the color.

For example:

console.log('\x1b[33m%s\x1b[0m', 'hi!') 

If you type the code in Node.js REPL, then CDMY67CDMY will be yellow.

The considered method is rather laborious. The easiest way to colorize console output is to use the library. One such library is the Chalk , which, in addition to defining color, allows you to make text bold, oblique, or underlined.

Install the library using CDMY68CDMY and use it as follows:

const chalk=require('chalk') console.log(chalk.yellow('hi!')) 

Using CDMY69CDMY is much simpler than memorizing complex sequences. It also makes the code more readable.

Creating a progress indicator

Progress is a great library for creating progress indicators in the terminal. Install it using CDMY70CDMY.

This snippet creates a progress indicator consisting of 10 steps. Every 100 ms, one step is performed. When filling out the indicator, we turn off the counter:

const ProgressBar=require('progress') const bar=new ProgressBar(':bar', { total: 10 }) const timer=setInterval(() => { bar.tick() if (bar.complete) clearInterval(timer) }, 100) 

Thank you for your attention, friends. If you find errors and typos do not hesitate to write in PM, I will be grateful.

To be continued….

Source