A Quick Guide to Node.js in 2019

Introduction

What Is Node.js?

Node.js is both open source and free, and is used for a variety of purposes. To name a few, Node.js is very efficient for serving dynamic content. If you want a quick and efficient way to get a blog up and running, Node.js can simplify the process. Based on JavaScript, Node.js can be used by most web developers who wish to perform server-side operations without having to learn a completely new language. Node.js is also very memory efficient, handles all requests asynchronously, and the included package manager has access to the largest repository in the world.

Advantages

Node.js has several advantages, such as the following:

  • Natively supports asynchronous tasks. For example, when a user makes a request to a Node.js-written script, Node.js continues to be available for new requests while processing the current request.
  • Supports most Linux distributions and has a large number of pre-written packages available for you to use.
  • Has most of the basic functions you will need built-in. This includes the ability to edit, move or delete files; as well as interact with MySQL, MongoDB, and a plethora of other things without having to use the included package manager.
  • Uses the largest repository of packages in the world: npm.
  • Similar code syntax to JavaScript. Node.js is essentially server-side JS.

Disadvantages

Unfortunately, though, Node.js does have it's share of disadvantages:

  • As it is a relatively new language, compared to something like PHP, it's codebase is updated often. This means that calls or methods you use may not work in a previous or future version of Node.js.
  • Node.js may occasionally take longer to write code for, as it can not easily use other libraries. ImageMagick, for example, is a popular library used on PHP that is not supported with Node.js.
  • Unlike Java, exceptions are difficult to implement. This means that it is nearly impossible to find errors in your code if you have a JS file that is thousands of lines long.

Using Node.js

Prerequisites

  • Any modern version of Ubuntu, CentOS, or Debian installed. This article will only cover the installation process for CentOS.
  • A minimum of 256 MB of RAM. Note, this figure depends on the application that you'll be running.
  • For this tutorial, you'll also need a text editor, such as Vim or Nano.

Installing Node

Update your package manager:

yum update -y

Install Node.js:

yum install nodejs -y

If you are prompted to import a key, enter Y to continue.

Ensure the installation was successful:

node -v
npm -v

Basic File Type Conventions

All Node.js files must end with .js. For example, a simple quadratic solver can be called Quadratic.js. Having said that, you can call it whatever you'd like as long as the first requirement is met.

The API

Programming languages usually have an API available, and Node.js is no exception. If you are lost or need to find the syntax for a function (or method), check out the Node.js docs.

NOTE: As mentioned previously, Node.js has a code-base that is updated constantly and as such, functions here may no longer work in later versions.

Creating Your First Programs

Hello, World!

In this section, we'll be learning about the most basic program you can create. To begin, head to /~ or /root. Creating your first project is as simple as creating a JS file:

nano HelloWorld.js

Once you are inside your favourite text editor, enter the following:

// For reference, comments are made using '//' added before or after a line. Comments are ignored by the Node.js interpreter.
console.log("Hello, world!"); // console.log() simply outputs text to the terminal.

Exit and save.

Now, launch your program:

node HelloWorld.js

You will see the following output:

[root@test-server ~]# node HelloWorld.js
Hello, world!

Simple Math & Variables

In this section, we'll be learning how to perform basic mathematical operations. To begin, head to your /root directory again and create a file called MathTest.js:

nano MathTest.js 

Paste the following code into the file:

var a = 5; // Variables are declared using 'var variableName = value'. The value can be a string, integer, boolean value (ie. true/false) or an object. 
var b = 10;
var c = "Hello, world!";

console.log(c); // This line will output the contents of variable c.
console.log("a = " + a + ", b = " + b); // This line prints out the respective values for a & b.
console.log("a + b = " + (a + b)); // This line prints out the result of (a + b) or (5 + 10). The result should be 15.

Save and exit.

When you execute your MathTest.js program, you will see the following:

[root@test-server ~]# node MathTest.js
Hello, world!
a = 5, b = 10
a + b = 15

Starting Our First Webserver

In this section, we'll be learning how to start up a Node.js webserver. To begin, create a file called WebTest.js:

nano WebTest.js

Paste the following code:

 // This line includes the HTTP module. Having it included allows us to use it's methods and functions to start a working webserver.
var http = require("http");
var a = 5, b = 10; 

http.createServer(function (request, response) {
    // This will simply output "Request received!" to your terminal when you visit your page.
    console.log("Request received!");

    // This line tells your browser that it should be expecting HTML content to be returned.
    response.writeHead(200, {'Content-Type': 'text/html'}); 

    // The following line adds "Hello, world! a + b = 15" to the body. The <i></i> tags will italicize the text. 
    response.write("<i>Hello, world! a + b = " + (a + b) + "</i>"); 

    // Finally, we'll tell the browser that we're done sending data with 'response.end()' below.
    response.end(); 
}).listen(8080);

Once you've saved the file, run your new program:

[root@test-server ~]# node WebTest.js

Now, visit http://(YOUR_SERVER_IP):8080. Make sure to have your firewall configured correctly to allow the request.

You will see Request received! on your terminal and the following in your browser:

Hello, world! a + b = 15

NOTE: In order to close (shut down) WebTest.js, use the following key combination: CTRL + C.

Now that you understand some of the basics, the following section will introduce you to using 3rd party modules, installed via npm.

Installing a 3rd Party Module and Using It in a Program

In this section, we'll be extending our first "Hello, world!" program. To begin, we'll be installing a package called colo. This package allows us to use colours on the terminal.

To begin, we'll be using npm to install the package:

npm i colo  

For reference, you can remove the package with npm remove colo

Once the process completes, you will have access to the colo package. Now, once you've opened HelloWorld.js up, add the following line at the top:

var colour = require("colo");

Where you see console.log(...), encapsulate "Hello, world!" with brackets. At the start of the brackets, add colour.red.bold:

console.log(colour.red.bold("Hello, world!"));

Your final code will look like the following:

var colour = require("colo");
console.log(colour.red.bold("Hello, world!"));

Save, exit and run your program. The output will be exactly the same as before, except "Hello, world!" will now be red (and bold) in your terminal.

Final Remarks

Congratulations on completing all the basic programs. This should provide you with the knowledge to interpret (at least most) of the code used in other tutorials. Hopefully, you don't stop here — there are many other things that you can do with Node.js!

If you find that Node.js isn't the language for you, removing it is as simple as the following:

yum remove nodejs -y

Dejar un comentario

ZPanel y Sentora en CentOS 6 x64

ZPanel y Sentora en CentOS 6 x64

ZPanel, un panel de control de alojamiento web popular, se bifurcó en 2014 a un nuevo proyecto llamado Sentora. Aprende a instalar Sentora en tu servidor con este tutorial.

Cómo instalar Vtiger CRM Open Source Edition en CentOS 7

Cómo instalar Vtiger CRM Open Source Edition en CentOS 7

Aprende cómo instalar Vtiger CRM, una aplicación de gestión de relaciones con el cliente, en CentOS 7 para aumentar tus ventas y mejorar el servicio al cliente.

Cómo instalar el servidor Counter-Strike 1.6 en Linux

Cómo instalar el servidor Counter-Strike 1.6 en Linux

Esta guía completa le mostrará cómo configurar un servidor Counter-Strike 1.6 en Linux, optimizando el rendimiento y la seguridad para el mejor juego. Aprende los pasos más recientes aquí.

¿Puede la IA luchar con un número cada vez mayor de ataques de ransomware?

¿Puede la IA luchar con un número cada vez mayor de ataques de ransomware?

Los ataques de ransomware van en aumento, pero ¿puede la IA ayudar a lidiar con el último virus informático? ¿Es la IA la respuesta? Lea aquí, sepa que la IA es una bendición o una perdición

ReactOS: ¿Es este el futuro de Windows?

ReactOS: ¿Es este el futuro de Windows?

ReactOS, un sistema operativo de código abierto y gratuito, está aquí con la última versión. ¿Puede satisfacer las necesidades de los usuarios de Windows de hoy en día y acabar con Microsoft? Averigüemos más sobre este estilo antiguo, pero una experiencia de sistema operativo más nueva.

Manténgase conectado a través de la aplicación de escritorio WhatsApp 24 * 7

Manténgase conectado a través de la aplicación de escritorio WhatsApp 24 * 7

Whatsapp finalmente lanzó la aplicación de escritorio para usuarios de Mac y Windows. Ahora puede acceder a Whatsapp desde Windows o Mac fácilmente. Disponible para Windows 8+ y Mac OS 10.9+

¿Cómo puede la IA llevar la automatización de procesos al siguiente nivel?

¿Cómo puede la IA llevar la automatización de procesos al siguiente nivel?

Lea esto para saber cómo la Inteligencia Artificial se está volviendo popular entre las empresas de pequeña escala y cómo está aumentando las probabilidades de hacerlas crecer y dar ventaja a sus competidores.

La actualización complementaria de macOS Catalina 10.15.4 está causando más problemas que resolver

La actualización complementaria de macOS Catalina 10.15.4 está causando más problemas que resolver

Recientemente, Apple lanzó macOS Catalina 10.15.4, una actualización complementaria para solucionar problemas, pero parece que la actualización está causando más problemas que conducen al bloqueo de las máquinas Mac. Lee este artículo para obtener más información

13 Herramientas comerciales de extracción de datos de Big Data

13 Herramientas comerciales de extracción de datos de Big Data

13 Herramientas comerciales de extracción de datos de Big Data

¿Qué es un sistema de archivos de diario y cómo funciona?

¿Qué es un sistema de archivos de diario y cómo funciona?

Nuestra computadora almacena todos los datos de una manera organizada conocida como sistema de archivos de diario. Es un método eficiente que permite a la computadora buscar y mostrar archivos tan pronto como presiona buscar.