Node.js tutorial, part 2: JavaScript, V8, some development techniques

https://medium.freecodecamp.org/the-definitive-node-js-handbook-6912378afc6e
  • Transfer
  • Tutorial
Publishing the first part of the translation of this guide to Node.js, we decided to find out the opinion of the audience about whether we should continue to work on the project, and conducted a small survey. As it turned out, approximately 94% of those who voted supported our initiative. Therefore, meet the second part of the Node.js guide. Today we will talk about what kind of knowledge in the field of JS you need to have in order to productively develop applications for the Node.js platform, discuss the differences between browser and server JavaScript code, talk about JS engines and some techniques of Node.js development.






What JS knowledge you need to have for Node.js development?


Suppose you just started programming. How deeply do you need to learn JavaScript to successfully master Node.js? It’s difficult for a beginner to reach a level where he gains sufficient confidence in his professional skills. In addition, while studying programming, you may feel that you do not understand exactly where browser JavaScript ends and development for Node.js begins.

If you are at the very beginning of the JavaScript programmer’s path, I would advise you, before writing for Node.js, to master the following language concepts well:

  • Lexical constructions.
  • Expressions.
  • Types.
  • Variables.
  • Functions.
  • Keyword this.
  • Arrow functions
  • Cycles
  • Scopes.
  • Arrays
  • Template lines.
  • Use semicolon.
  • Work in strict mode.

In fact, this list can be continued, but if you master all this, it means that you will lay a good foundation for productive client and server development in JavaScript.
The following language concepts are also very important for understanding asynchronous programming ideas, which are one of the basic parts of Node.js. In particular, we are talking about the following:

  • Asynchronous programming and callback functions.
  • Timers.
  • Promises
  • Async / await construction.
  • Closures
  • The cycle of events.

There are many materials on JavaScript that allow beginners to master the language. For example, here is the training course of the author of this manual, here is a very useful section of MDN, here is a tutorial on javascript.ru. Learn the basic JavaScript mechanisms at freecodecamp.com .

Above, we talked about the fact that beginners may be bothered by the question of where the boundary between server-side and client-side JavaScript is located. Let's talk about it.

Differences between the Node.js platform and the browser


How does JS development for Node.js differ from browser programming? The similarity between these environments is that the same language is used both there and there. But developing applications designed to run in a browser is very different from developing server applications. Despite the use of the same language, there are some key differences that transform these two types of development into completely different occupations.

It should be noted that if the one who was previously engaged in the front-end, begins to learn Node.js, he has a very serious opportunity to quickly learn everything that is needed due to the fact that he will write in a language he already knows. If the necessity to learn a new language is added to the need to master a new environment, the task becomes much more complicated.
So the main difference between the client and the server is in the environment for which it is necessary to program, in the ecosystems of these environments.

In the browser, the bulk of the work has to do with various operations with web documents via the DOM, as well as using other web platform APIs, such as, say, mechanisms for working with cookies. All this in Node.js, of course, no. There is no object document, no object window, as well as other objects provided by the browser.

The browser, in turn, does not have those software mechanisms that exist in the Node.js environment and exist as modules that can be connected to the application. For example, this is the API for accessing the file system.

Another difference between client and server development on JS is that when working in the Node.js environment, the developer completely controls the environment. Unless you are developing an open source application that can be run anywhere, you know for example what version of Node.js your project will run on. This is very convenient compared to the client environment, where your code has to work in the user's browser. In addition, this means that you can, without fear of problems, use the latest features of the language.

Since JavaScript is developing extremely rapidly, browsers simply do not have enough time to quickly implement all of its innovations. In addition, not all users work on the latest versions of browsers. As a result, developers who want to use something new in their programs are forced to take this into account, to take care of the compatibility of their applications with the browsers in use, which may result in the rejection of modern JavaScript features. You can, of course, use the Babel transpiler to convert the code into a format compatible with the EcmaScript 5 standard, which all browsers support, but you don’t need this when working with Node.js.

Another difference between Node.js and browsers is that NoJe.js uses the CommonJS module system.while in browsers one can observe the beginning of the implementation of the ES Modules standard. In practice, this means that at the present time in Node.js, to connect an external code, the construction is used require(), and in the browser code - import.

V8 and other JavaScript engines


V8 is the name of the JavaScript engine used in the Google Chrome browser. It is he who is responsible for the execution of JavaScript-code, which gets into the browser when working on the Internet. V8 provides a runtime environment for javascript. DOM and other web platform APIs are provided by the browser.

JS-engine is independent of the browser in which it works. It is this fact that made possible the emergence and development of the Node.js platform. V8 was chosen as the engine for Node.js in 2009. As a result, the explosive growth in the popularity of Node.js V8 turned out to be the engine, which is now responsible for the execution of a huge amount of server-side JS-code.

The Node.js ecosystem is huge. Because of this, V8 is also used, through projects like Electron , in the development of desktop applications.

It should be noted that, in addition to the V8, there are other engines:


The list of JS engines is not limited to this.

These engines implement the ECMA-262 specification, also called ECMAScript. It is this specification that standardizes JavaScript. The latest version of the standard can be found here .

▍ Development of JS engines and the desire for performance


The V8 engine is written in C ++, it is constantly being improved. It can run on many systems, in particular, on Mac, Windows and Linux. Here we will not talk about the details of the implementation of the V8. Information about them can be found in other publications, including - on the official website V8 . They change over time, sometimes very seriously.

V8 is constantly evolving, the same can be said about other engines. This leads, in particular, to an increase in the performance of web browsers and the Node.js platform. Manufacturers of browser engines are constantly competing, fighting for the speed of code execution, this has been going on for many years. All this benefits users and programmers.

▍ Interpretation and compilation


JavaScript is considered to be an interpreted language, but modern engines are far from just interpreting JS code. They compile it. This trend can be observed from 2009, when the JavaScript compiler was added to Firefox 3.5, after which other manufacturers of engines and browsers adopted this idea.

V8 compiles javascript to improve code performance. Since the advent of Google Maps in 2004, JavaScript has evolved, evolved from a language in which, in order to realize the interactive capabilities of web applications, they usually wrote several dozen lines into a language in which browser applications consisting of thousands or even hundreds are written. thousands of lines of code. Such applications can be executed in the browser for hours, which is very different from the old JS usage scenarios, the code on which, for example, could be used only to check the correctness of the data entered into forms. In modern conditions, compiling code makes a huge sense, since, although the execution of this step can postpone the moment the code runs, after compiling the code is much more productive than the one

Now, having discussed some of the provisions relating to JS-engines, interpretation and compilation of the code, let's move on to practice. Namely, let's talk about how to shut down Node.js applications.

Exit the Node.js application


There are several ways to shut down Node.js applications.

So, when you run the program in the console, you can complete its work using the keyboard shortcut ctrl+c. But we are more interested in software ways to shut down applications. And we will begin, perhaps, with the coarsest command to exit the program, which, as you will now understand, it is better not to use.

The kernel module processprovides a convenient method that allows you to programmatically exit from a Node.js application. It looks like this:

process.exit()

When Node.js encounters such a command in the code, this causes its process to end instantly. This means that absolutely everything the program has been doing will be rather rude and unconditionally interrupted. We are talking about unsolicited callbacks, network requests that were executed at the time of the exit, about actions with files, about write operations to stdoutor stderr.

If you are satisfied with this state of affairs, you can use this method. When you call it, you can pass it an integer that will be perceived by the operating system as an exit code from the program.

process.exit(1)

By default, this code is set to 0, which means a successful shutdown. Other exit codes have other meanings that may be useful for using them in their own system in order to interact with one program.
Details about the exit codes of programs can be found here .

An exit code can also be assigned to a property process.exitCode. It looks like this:

process.exitCode = 1

After the program finishes, Node.js will return this code to the system.

It should be noted that the work of the program will end on its own in a natural way after it performs all the actions specified in it. However, in the case of Node.js, there are often programs that, in ideal conditions, are designed to work for an indefinite duration. We are talking, for example, about HTTP-servers like this:

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

Such a program, if nothing happens, in theory, can work forever. In this case, if called process.exit(), the operations performed by it at the moment of calling this command will be interrupted. Is that bad.

To complete the work of such programs, you need to use a signal SIGTERMand perform the necessary actions using the appropriate handler.

Please note that in order to use an object, processyou do not need to connect anything with require, as this object is available to Node.js applications by default.

Consider the following example:

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

What are “signals”? Signals are tools for interfacing processes in the POSIX (Portable Operating System Interface) standard. They are notifications sent to the process in order to inform it about certain events.

For example, a signal SIGKILLtells the process that it needs to shut down immediately. He, ideally, works just like process.exit().

The signal SIGTERMinforms the process that it needs to perform a normal shutdown procedure. Such signals are sent from process managers, like upstartor supervisord, and from many others.

You can also send such a signal from the program itself using the following command:

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

For successful execution of such a command, you need to know the PIDprocess that is planned to be completed.

Reading environment variables from Node.js


The kernel module processhas a property envthat gives access to all environment variables that were set at the time the process started.

Here is an example of working with an environment variable NODE_ENV, which, by default, is set to development:

process.env.NODE_ENV // "development"

If, before running the script, to set it to a value production, it will inform Node.js that the program is running in the production environment.

Similarly, you can work with other environment variables, for example, with those that you set yourself.

Results


Today we touched upon issues of browser and server programming in JavaScript, talked about JS engines, how to shut down server applications, and how to read environment variables from Node.js programs. Next time we will talk about hosting for Node.js applications, how to use Node.js in REPL mode, working with arguments that can be passed to scripts when they are called, about interaction with the console, and how to design the code modules.

Dear readers! What javascript tutorials would you recommend for beginners?


Also popular now: