Node.js Part 1 Guide: General Information and Getting Started

Original author: Flavio Copes
  • Transfer
  • Tutorial
We are starting to publish a series of materials that are a step-by-step translation of the Node.js guide for beginners. Namely, in this case the “beginner” is the one who has some knowledge of browser JavaScript. He heard that there is a server platform, programs for which are also written to JS, and would like to master this platform. Perhaps you will find here something useful for yourself and if you are already familiar with Node.js.

By the way, last year we had a similar in size project dedicated to bash scripts. Then we, after publishing all the planned materials, collected them as a PDF file . It is also planned to do this time.



Today we will discuss the features of Node.js, we will begin our acquaintance with the ecosystem of this platform and write the server “Hello World”.


Node.js Overview


Node.js is an open source, cross-platform JavaScript runtime that runs on servers. Since the release of this platform in 2009, it has become extremely popular and today plays a very important role in the field of web development. If we take as an indicator of the popularity of the number of stars that a certain project gathered on GitHub, then Node.js , which has more than 50,000 stars, is a very, very popular project.

Node.js platform is built on the basis of JavaScript engine V8 from Google, which is used in Google Chrome browser. This platform is mainly used to create web servers, but its scope is not limited to this.

Consider the main features of Node.js.

▍Speed


One of the main attractive features of Node.js is speed. JavaScript code running in Node.js can be twice as fast as code written in compiled languages ​​like C or Java, and orders of magnitude faster than interpreted languages ​​like Python or Ruby. The reason for this is the non-blocking platform architecture, and the specific results depend on the performance tests used, but, in general, Node.js is a very fast platform.

▍Easy


Node.js platform is easy to learn and use. In fact, it is really very simple, especially noticeable in comparison with some other server platforms.

▍JavaScript


In the Node.js environment, code written in JavaScript is executed. This means that millions of front-end developers who already use JavaScript in the browser can write both server and client code in the same programming language without having to learn a completely new tool for moving to server development.

The same language concepts are used in the browser and on the server. In addition, in Node.js, you can quickly switch to the use of new ECMAScript standards as they are implemented on the platform. You do not need to wait for this until users refresh their browsers, since Node.js is a server environment that the developer fully controls. As a result, new language features are available when installing the version of Node.js that supports them.

V V8 engine


Node.js, among other solutions, is based on Google’s open source JavaScript V8 engine from Google Chrome and other browsers. This means that Node.js is using the work of thousands of engineers who have made Chrome's JavaScript runtime incredibly fast and continue to work towards improving the V8.

▍ Asynchrony


In traditional programming languages ​​(C, Java, Python, PHP), all instructions, by default, are blocking, unless the developer explicitly takes care of asynchronous code execution. As a result, if, for example, in such an environment, to make a network request to download some JSON code, the execution of the stream from which the request was made will be suspended until the response is received and processed.

JavaScript greatly simplifies writing asynchronous and non-blocking code using a single stream, callback functions (callbacks), and an event-based development approach. Every time we need to perform a heavy operation, we pass the callback to the appropriate mechanism, which will be called immediately after the completion of this operation. As a result, in order for the program to continue, it is not necessary to wait for the results of such operations.

A similar mechanism originated in browsers. We cannot afford to wait, say, the end of an AJAX request, without being able to respond to user actions, such as clicking on buttons. In order to make it convenient for users to work with web pages, everything, and downloading data from the network, and processing button presses, must occur simultaneously, in real time.

If you have ever created an event handler for clicking a button, then you have already used asynchronous programming techniques.

Asynchronous mechanisms allow a single Node.js server to simultaneously process thousands of connections without loading the programmer with thread management tasks and organizing parallel code execution. Such things are often sources of error.

Node.js provides the developer with non-blocking basic input-output mechanisms, and, in general, the libraries used in the Node.js environment are written using non-blocking paradigms. This makes blocking behavior an exception rather than the norm.

When Node.js needs to perform an I / O operation, such as loading data from a network, accessing a database or a file system, instead of blocking waiting for the results of such an operation the main thread, Node.js initiates its execution and continues to do other things until until the results of this operation are obtained.

▍ Libraries


Thanks to the simplicity and convenience of working with the package manager for Node.js, which is called npm , the Node.js ecosystem is thriving. Now in the npm registry there are more than half a million open source packages that any Node.js developer can use freely.
Having reviewed some of the main features of the Node.js platform, let's try it out in action. Let's start with the installation.

Installing Node.js


Node.js can be installed in various ways, which we will now consider.
So, the official installation packages for all major platforms can be found here .

There is another very convenient way to install Node.js, which is to use the package manager available in the operating system. For example, the macOS package manager, which is the de facto standard in this area, is called Homebrew . If it is on your system, you can install Node.js by running this command from the command line:

brew install node

A list of package managers for other operating systems, including Linux and Windows, can be found here .

A popular version manager for Node.js is nvm . This tool allows you to conveniently switch between different versions of Node.js, with its help you can, for example, install and try a new version of Node.js, after which, if necessary, return to the old one. Nvm is useful in a situation where you need to try out some code on the old version of Node.js.

I would advise beginners to use the official Node.js installers. I would recommend macOS users to install Node.js using Homebrew. Now that you've installed Node.js, it's time to write “Hello World”.

First Node.js application


The most common example of the first application for Node.js is a simple web server. Here is his code:

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

To run this code, save it in a file server.jsand execute the following command in a terminal:

node server.js

To check the server, open any browser and type in the address bar http://127.0.0.1:3000, that is, the address of the server that will be displayed in the console after its successful launch. If everything works as it should - the page will display “Hello World”.

Let us examine this example.

First, note that the code contains the command for connecting the http module .

Node.js platform is the owner of a wonderful standard set of modules , which includes well-developed mechanisms for working with the network.

The createServer()object method httpcreates a new HTTP server and returns it.

The server is configured to listen on a specific port on a given host. When the server is ready, the corresponding callback is called, informing us that the server is running.

When the server receives a request, an event is raised requestthat provides two objects. The first is the request ( req, the http.IncomingMessage object ), the second is the response ( res, the http.ServerResponse object ). They are the most important mechanisms for handling HTTP requests.

The first provides information about the request. In our simple example, we do not use this data, but, if necessary, with the help of an object, reqwe can access the request headers and the data transmitted in it.

The second is needed to form and send a response to the request.

In this case, the answer to the request we form as follows. First, we set the property statusCodeto a value 200, which indicates that the operation was successful:

res.statusCode = 200

Next, we set the title Content-Type:

res.setHeader('Content-Type', 'text/plain')

After that, we finish preparing the response by adding its contents as an argument to the method end():

res.end('Hello World\n')

We have already said that a powerful ecosystem has developed around the Node.js platform. Now let's discuss some popular frameworks and support tools for Node.js.

Node.js frameworks and support tools


Node.js is a low-level platform. In order to simplify the development for it and make life easier for programmers, a huge number of libraries were created. Some of them have become very popular over time. Here is a small list of libraries that I consider well done and worth exploring:

  • Express . This library provides the developer with an extremely simple but powerful tool for creating web servers. The key to the success of Express was a minimalist approach and focus on basic server mechanisms without attempting to impose a certain vision of the “only correct” server architecture.
  • Meteor . This is a powerful fulsteck framework that implements an isomorphic approach to developing applications in JavaScript and using code on both the client and the server. Once Meteor was a standalone tool, which includes everything that a developer may need. Now it is also integrated with front-end libraries, such as React , Vue and Angular . Meteor, in addition to the development of conventional web applications, can be used in mobile development.
  • Koa . This web framework was created by the same team that works on Express. During its development, which was based on years of experience with Express, attention was paid to the simplicity of the solution and its compactness. This project appeared as a solution to the problem of making major changes in Express, incompatible with other framework mechanisms that could split the community.
  • Next.js . This framework is designed to organize server rendering of React applications.
  • Micro . This is a very compact library for creating asynchronous HTTP microservices.
  • Socket.io . This is a library for developing real-time network applications.

In fact, in the Node.js ecosystem, you can find a supporting library for solving almost any task. As you understand, building a similar ecosystem takes a lot of time. Node.js platform appeared in 2009. During its existence, a lot of things happened that are worth knowing to a programmer who wants to learn this platform.

A brief history of Node.js


This year, Node.js is 9 years old. This, of course, is not so much if we compare this age with the age of JavaScript, which is already 23 years old, or with the 25-year-old age of the web, which exists in a form in which we know it, if we consider the appearance of the Mosaic browser.

9 years is a short time for technology, but now it seems that the Node.js platform has always existed.

I started working with Node.js from earlier versions of the platform when it was still only 2 years old. Even then, although there was not so much information about Node.js, it was already possible to feel that Node.js is very serious.

Now let's talk about the technologies that underlie Node.js and briefly look at the main events related to this platform.

So, JavaScript is a programming language that was created in Netscape as a scripting language designed to manage web pages in the Netscape Navigator browser .

Part of Netscape's business was the sale of web servers, which included an environment called Netscape LiveWire. She allowed to create dynamic web pages, using server JavaScript. As you can see, the idea of ​​using JS for server development is much older than Node.js. This idea is almost as old as JavaScript itself, but in the times in question, server-side JS has not gained popularity.

One of the key factors due to which the Node.js platform has become so widespread and popular is the time of its appearance. So, a few years before this, JavaScript began to be considered a serious language. This happened thanks to Web 2.0 applications, like Google Maps or Gmail, which demonstrated to the world the capabilities of modern web technologies.

Thanks to the browser browser war, which continues to this day, JavaScript engine performance has increased dramatically. The development teams behind the main browsers work every day to improve the performance of their solutions, which has a beneficial effect on JavaScript in general. One of these engines is the already mentioned V8 used in the Chrome browser and used in Node.js. It is one of the results of the desire of browser developers for high performance JS-code.

Of course, the popularity of Node.js is based not only on a successful set of circumstances and on the fact that this platform appeared at the right time. She presented to the world an innovative approach to server-side development in JavaScript. Consider the major milestones in the history of Node.js.

▍2009


  • The appearance of Node.js
  • Creating the first option npm .

▍2010



▍2011


  • Exit npm 1.0.
  • Large companies, such as LinkedIn and Uber , started using Node.js.

▍2012


  • The rapid rise in popularity of Node.js.

▍2013


  • The advent of Ghost , the first major publishing platform using Node.js.
  • Koa release .

▍2014


  • This year there have been dramatic events. There was a project IO.js , which is a fork of Node.js, the purpose of which, among other things, was to introduce support for ES6 and accelerate the development of the platform.

▍2015


  • Foundation of the Node.js Foundation .
  • Merge IO.js and Node.js.
  • In npm, it is possible to work with private modules.
  • Exit Node.js 4 (it should be noted that this platform did not have versions 1, 2 and 3).

▍2016


  • Incident with the left-pad package .
  • The appearance of Yarn .
  • Exit Node.js 6.

▍2017


  • In npm they start to pay more attention to security.
  • Node.js output 8
  • The emergence of support for HTTP / 2 .
  • V8 is officially recognized as a JS engine, designed not only for Chrome, but also for Node.
  • 3 billion downloads from npm are done weekly.

▍2018


  • Exit Node.js 10.
  • Support for ES modules .
  • Experimental mjs support .

Results


Today you familiarized yourself with the Node.js platform, sorted out its installation, wrote and tested the first simple application. Next time we will talk about how much knowledge in the field of JavaScript you need to have for successful development for Node.js, about the difference between browser and server JS-code, and discuss some techniques of Node.js-development.

Dear readers! Tell me, did you start Hello World for Node.js?

The following parts of the manual:
Part 1: General information and getting started
Part 2: JavaScript, V8, some development techniques
Part 3: Hosting, REPL, work with the console, modules
Part 4: npm, package.json and package-lock.json files
Part 5: npm and npx
Part 6: event loop, call stack, timers
Part 7: asynchronous programming

Only registered users can participate in the survey. Sign in , please.

Does translation of a series of articles about Node.js continue?


Also popular now: