Node.js tutorial, part 3: hosting, REPL, work with console, modules

https://medium.freecodecamp.org/the-definitive-node-js-handbook-6912378afc6e
  • Transfer
  • Tutorial
This is the third part of the translation of the Node.js guide. Today we will talk about choosing hosting for Node.js projects, how to work with Node.js in the REPL mode and how to run scripts with arguments, about interaction with the console and about modules.




Hosting for Node.js applications


The choice of hosting for Node.js applications depends on your needs. Here is a small list of hosting options that you can explore by deciding to deploy your application and make it publicly available. First, consider the simple options, the possibilities of which are limited, and then - more complex, but also have more serious features.

▍The simplest hosting option: local tunnel


Even if your computer is assigned a dynamic IP address or you are behind NAT, you can deploy your application on it and serve user requests to it using a local tunnel.

This option is suitable for quick testing organization, in order to arrange a product demonstration, or to give an application to a very small group of people.

For the organization of local tunnels there is a very good service, ngrok , available for many platforms.

Using ngrok, it is enough to execute a command of a type ngrok PORTand the port specified by you will be available from the Internet. At the same time, if you use the free version of the service, you will have an address in the domainngrok.io. If you decide to make a paid subscription, you can use your own domain names, and, in addition, you can increase the security of the solution (using ngrok, you open access to your computer all over the Internet).

Another tool that can be used to organize local tunnels is called localtunnel .

▍Meduals for deploying Node.js projects that do not require configuration


Glitch


Glitch is an interactive environment and platform for rapid application development, which allows you to deploy them in glitch.com subdomains. This platform does not support its own user domains yet; there are some limitations when working with it , but it is great for working on application prototypes. The design of the Glitch looks pretty funny (perhaps it can be written into the advantages of this platform), but this is not some kind of “toy”, a very limited environment. Here you have the opportunity to work with Node.js, CDN, secure storage for confidential information, the ability to exchange data with GitHub and much more.

The Glitch project is run by the same company behind FogBugz and Trello (which is also one of the creators of StackOverflow). I often use this platform to demonstrate applications.

Codepen


Codepen is a great platform around which an interesting community has been formed. Here you can create projects that include many files, and deploy them using your own domain.

▍Server environments


Serverless platforms allow you to publish applications without worrying about servers at all, about setting them up or managing them. The paradigm for serverless computing is that applications are published as functions that respond to calls to the network endpoint. Such an approach to the deployment of applications is also called FAAS (Functions As A Service, function as a service).

Here are a couple of popular solutions in this area:


Both of these projects provide the developer with a certain level of abstraction that allows publishing applications on various FAAS platforms, for example, on Amazon AWS Lambda, on Microsoft Azure and on Google Cloud.

▍PAAS solutions


PAAS (Platform As A Service, platform as a service) are platforms that take care of many things that, under normal conditions, the developer should take care of when deploying the application.

Zeit Now


Zeit is an interesting option for deploying applications. Deployment, when using this platform, comes down to typing a command in the terminal now. There is a free version of Zeit, there are some limitations when working with it. There is also a paid, more powerful version of this platform. Using Zeit, you can simply not think that you need a server to run your application. You simply deploy the application, and everything else is managed by this platform.

Nanobox


The creators of the Nanobox platform , which includes the deployment of Node.js applications, call it PAAS V2.

Heroku


Heroku is another great platform for hosting Node.js applications. Here is a good article on how to work with it.

Microsoft Azure


Azure is a cloud platform from Microsoft. In its documentation there is a section dedicated to Node.js applications.

Google Cloud Platform


Google Cloud is a great environment for deploying Node.js applications. Here is the relevant section of its documentation.

▍VPS hosting


There are many platforms that provide VPS hosting services . A common feature of such platforms is the fact that a developer gets a virtual server at his disposal, independently installs an operating system (Linux or Windows) on it, and independently develops applications.

Among the platforms that provide VPS services, of which there are a great many, we can note the following, which I used and which I could recommend to others:


From our side , we add that RUVDS also provides VPS hosting services. We are licensed by FSTEC, our clients are insured by AIG, we have four data centers in different countries. We have our own RUCLOUD data center of TIER 3 level in Korolev, Moscow region, as well as tight areas in the data centers of Deltalis (Switzerland) , London Equinix LD8 (United Kingdom) , and MMTS-9 (Moscow, Russia). All germozones meet the level of reliability not lower than TIER 3.

The company’s partners are Finam JSC, BCS Financial Group, National Settlement Depository (Moscow Exchange), VTsIOM JSC, Gars-Telecom, Gett Taxi, delivery operator Delivery Club and many others.


▍ Normal server


Another hosting solution is to purchase (or rent, for example, using the Vultr Bare Metal service ) a regular server, install Linux and other software on it, connect it to the Internet and host Node.js applications on it.

Hosting is a huge topic, but we hope the materials in this section will allow you to choose exactly what you need. Now let's move on to the story about working with Node.js in the REPL mode.

Using Node.js in REPL Mode


The REPL abbreviation stands for Read-Evaluate-Print-Loop (the cycle “read-calculate-output”). Using REPL is a great way to quickly explore the possibilities of Node.js.

As you already know, to run scripts in Node.js the command is used node, it looks like this:

node script.js

If you enter the same command, but do not specify the file name, Node.js will be launched in the REPL mode:

node

If you try now to enter such a command in your terminal, you will see something like the result:

> node
>

Node.js is now in standby mode. The system is waiting for us to enter some JavaScript code on the command line that it will execute.

First, let's try something very simple:

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

Here we suggested Node.js to execute the command used to output data to the console. The first value test,, is what the command output console.log('test'). The second value,, undefinedis what the function returned console.log().

After the command is completed, the REPL prompt appears, which means that we can enter a new command here.

▍Completion of commands with the Tab key


REPL is an interactive environment. If in the process of writing the code, press a key Tabon the keyboard, the REPL will try to automatically complete the input by selecting, for example, the appropriate name of a variable you have already declared or the name of a standard object.

▍ JavaScript Object Exploration


Enter the name of a standard JavaScript object in the command line, for example Number, add a period after it and press the key Tab.

The REPL will list the properties and methods of the object with which the developer can interact:


Number Object Study

▍ Global Object Investigation


To find out which Node.js global objects you can work with, enter a command in the terminal global.and click Tab.


Study of global objects

▍Special variable _


The variable _(underscore) stores the result of the last operation performed. This variable can be used as part of commands entered into the console.

▍ Commands beginning with a point


In REPL mode, you can use some special commands that start with a dot. Here they are:

  • The command .helpdisplays reference information for commands beginning with a dot.
  • The command .editorputs the system into editor mode, which makes it easy to enter multi-line JavaScript code. After being in this mode, you will enter everything you want, use the command to run the code Ctrl+D.
  • The command .breakallows you to interrupt the input of a multi-line expression. Its use is similar to the use of shortcut keys Ctrl+C.
  • The command .clearclears the REPL context, and also interrupts the input of a multi-line expression.
  • The command .loadloads code from a javascript file into the current session.
  • The command .savesaves to the file everything that was entered during the REPL session.
  • The command .exitallows you to exit a REPL session; it acts in the same way as two consecutive keystrokes Ctrl+C.

It should be noted that the REPL recognizes the input of multi-line expressions and without using the command .editor.

For example, we began to enter an iterator code:

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

If, after entering the curly bracket, press the key Enter, the REPL will move to a new line, the invitation in which will look like three dots. This indicates that we can enter the code of the corresponding block. It looks like this:

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

Pressing Enterafter entering the last bracket will execute the expression. If you enter in this mode .break, the input will be aborted and the expression will not be executed.

The REPL mode is a useful Node.js feature, but its scope is limited to small experiments. We are also interested in something more than the ability to perform a couple of commands. Therefore, we proceed to working with Node.js as usual. Namely, let's talk about how Node.js scripts can take command line arguments.

Working with command line arguments in Node.js scripts


When you run Node.js scripts, you can pass arguments to them. Here is the usual script call:

node app.js

The arguments passed to the script can be either independent values ​​or constructions of the key-value type. In the first case, the launch of the script looks like this:

node app.js flavio

In the second - so:

node app.js name=flavio

What method of passing arguments is used depends on how you can work with them in the script code.

So, in order to get access to the command line arguments, the standard Node.js object is used process. It has a property argvthat is an array containing, among other things, the arguments passed to the script at startup.

The first element of the array argvcontains the full path to the file that is executed when the command is entered nodeon the command line.

The second element is the path to the script file to be executed.

All other elements of the array, starting with the third, contain what was passed to the script when it was launched.

Enumerate the arguments available inargv (this includes the path tonode, and the path to the executable script file), can be organized using a loop forEach:

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

If the first two arguments do not interest you, argvyou can form a new array on the basis , which will include all argvbut the first two elements:

const args = process.argv.slice(2)

Suppose, when running a script, only one argument was passed to it, in the form of an independent value:

node app.js flavio

Refer to this argument as follows:

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

Now we will try to use the key-value type construction:

node app.js name=flavio

With this approach, after the formation of the array args, there args[0]will be a string name=flavio. Before using the argument, this line must be parsed. The most convenient way to do this is to use the minimist library , which is designed to make it easier to work with command line arguments:

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

Now consider the output to the console.

Outputting data to the console using the console module


The standard module Node.js console gives the developer a lot of opportunities to interact with the command line during program execution. In general, this is the same as the object consoleused in browser-based JavaScript. Perhaps the simplest and most widely used method of the module consoleis console.log()that used to output the string data transmitted to it to the console. At the same time, if you pass an object to it, then it will be converted to its string representation before output. Several values ​​can be passed to the

method console.log():

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

After executing this sequence of instructions x, both the value and the value will fall into the console y.

To form complex strings, the command console.log()supports the use of wildcard characters, which, when outputting data, are replaced with the corresponding values ​​in the order of precedence.

For example, here is a command that displays the text My cat has 2 years:

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

Consider the features of wildcard characters:

  • %s formats the value as a string.
  • %dor %iformat the value as an integer.
  • %f formats the value as a floating point number.
  • %O used to display string representations of objects.

Here is another example of using wildcard characters:

console.log('%O', Number)

КонсолиCleaning console


To clear the console, use the command console.clear()(its behavior in different terminals may vary).

▍Counting of elements


We will now consider a useful method console.count(). Take a look at this code:

const x = 1const y = 2const z = 3console.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 method count()counts the number of line breaks and displays the result next to them.
Using this method, you can, in the following example, count apples and oranges:

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

▍Delete to the stack trace results console


Sometimes it is useful to display the function’s stack trace in the console. For example, in order to answer the question of how we got in a certain place of the program. You can do this with the following command:

console.trace()

Here is an example of its use:

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

This is what happened when I ran this code in REPL mode:

Trace
    atfunction2 (repl:1:33)
    atfunction1 (repl:1:25)
    atrepl:1:1
    atContextifyScript.Script.runInThisContext (vm.js:44:33)
    atREPLServer.defaultEval (repl.js:239:29)
    atbound (domain.js:301:14)
    atREPLServer.runBound[as eval] (domain.js:314:12)
    atREPLServer.onLine (repl.js:440:10)
    atemitOne (events.js:120:20)
    atREPLServer.emit (events.js:210:7)

▍ Measuring the time spent on performing some action


You can measure the time it takes, for example, to perform a function, using the console.time()and methods console.timeEnd(). It looks like this:

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

▍Work with stdout and stderr


As we have seen, the command is console.log()great for displaying messages in the console. It uses the so-called standard output stream, or stdout.

The command console.error()outputs the data to the standard error stream stderr. The data sent to stderr, get into the console, although what is displayed in this stream, you can, for example, redirect to the error log file.

▍ Using color when outputting data to the console


In order to color the texts output to the console, you can use escape sequences that identify colors:

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

If you execute this command, for example, in REPL mode, the text hiwill be displayed in yellow.
This approach, however, is not particularly convenient. To display color labels in the console, it will be convenient to use a specialized library, for example - chalk . In addition to the color formatting of texts, this library also supports other ways of styling them. For example, with its help you can make the text in bold, italic or underlined font.

To install it from npm, use the following command:

npm install chalk

You can use it like this:

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

Using the command is chalk.yellow()much more convenient than escape sequences, and the program text with this approach is much easier to read.

To learn more about chalk, check out this library ’s page on GitHub.

▍Create an operation progress indicator


The progress bar can be useful in different situations. To create progress indicators running in the console, you can use the progress package . You can install it like this:

npm install progress

Below is a sample code in which an indicator is created that can be used to display information about a certain task consisting of 10 steps. In our case, the execution of each step takes 100 ms. After the indicator is full, the command is called clearItnerval()and the program ends.

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

▍ Receive user input from the command line


How to make command line applications written for the Node.js platform interactive? Starting with version 7, Node.js contains a readline module that allows you to receive data from streams that can be read, for example, from process.stdin. This thread, during the execution of the Node.js program, is what is entered into the terminal. Data is entered one line at a time.

Consider the following code snippet:

const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
})
readline.question(`What's your name?`, (name) => {
  console.log(`Hi ${name}!`)
  readline.close()
})

Here we ask the user for his name, and after entering the text and pressing a key Enteron the keyboard, we display a greeting.

The method question()displays what is passed to it as the first parameter (that is, the question asked to the user) and waits for the input to complete. After clicking on Enterit, it calls the callback passed to it in the second parameter and processes what was entered. In the same callback we close the interface readline.

The module also readlinesupports other methods, the details of which you can find in the documentation referenced above.

If you, using this mechanism, need to ask the user for a password, then it is better not to display it, on input, on the screen, but to show the asterisk symbol instead of the entered characters *.

In order to do this, you can use the readline-sync package , the device of which is similar to the structure of the module readline, and which supports such features immediately after installation.

There is another package that provides a more complete and abstract solution to this problem. This is the inquirer package . You can install it like this:

npm install inquirer

With its use, the above example can be rewritten as follows:

const inquirer = require('inquirer')
var questions = [{
  type: 'input',
  name: 'name',
  message: "What's your name?",
}]
inquirer.prompt(questions).then(answers => {
  console.log(`Hi ${answers['name']}!`)
})

Package inquirer has extensive capabilities. For example, it can help ask a user a multiple choice question or form an interface with radio buttons on the console.

A programmer should be aware of the availability of alternative possibilities for performing certain actions in Node.js. In our case, this is a standard module readline, readline-sync and inquirer packages. The choice of a specific solution depends on the objectives of the project, on the availability of time for the implementation of certain capabilities and on the complexity of the user interface that is planned to be generated using the command line.

Node.js module system, using the exports command


Let's talk about how to use the API module.exportsin order to open access to the capabilities of the modules to other application files. Node.js has a built-in system of modules, each file being considered an independent module . The public functionality of the module, using the command require, can use other modules:

const library = require('./library')

This shows the import of the module library.js, the file of which is located in the same folder as the file that imports it.

A module, before it makes sense to import it, must export something, make it publicly available. To everything that is not explicitly exported by the module, there is no access from the outside. As a matter of fact, the API module.exportsallows you to organize the export of what will be available external to the module mechanisms.

Export can be organized in two ways.

The first is to write an object to module.exports, which is a standard object provided by the system of modules. This leads to the export of only the corresponding object:

const car = {
  brand: 'Ford',
  model: 'Fiesta'
}
module.exports = car
//..в другом файлеconst car = require('./car')

The second way is that the exported object is written to the property of the object exports. This approach allows you to export several objects from a module, including functions:

const car = {
  brand: 'Ford',
  model: 'Fiesta'
}
exports.car = car

The same can be rewritten and shorter:

exports.car = {
  brand: 'Ford',
  model: 'Fiesta'
}

In another file, use the fact that exported the module, you can:

const items = require('./items')
items.car

Or so:

const car = require('./items').car

What is the difference between writing an object in module.exportsand setting an object's properties exports?

In the first, the object is exported, which is recorded in module.exports. In the second case, the properties of this object are exported.

Results


Today we talked about hosting for Node.js applications, about REPL, about working with the command line, about the system of Node.js modules. Next time we will start a detailed conversation about npm, and, in particular, consider the features of files package.jsonand package-lock.json.

Dear readers! What hosting services do you use for your Node.js applications?


Also popular now: