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


Leave a Comment

Configuración de Adonis.js en Ubuntu 14

Configuración de Adonis.js en Ubuntu 14

Introducción Adonis.js es un MVC Framework para NodeJs que le permite escribir aplicaciones web con menos código. Toma prestados conceptos de otros marcos sólidos.

Cree una aplicación web Hapi.js usando Node.js en Ubuntu 16.04

Cree una aplicación web Hapi.js usando Node.js en Ubuntu 16.04

Hapi.js es un marco Node.js rico, robusto y poderoso diseñado para crear aplicaciones web en el ecosistema Node.js. Su diseño sencillo hace que

Cómo configurar PM2 en Ubuntu 16.04

Cómo configurar PM2 en Ubuntu 16.04

PM2 es un administrador de procesos Node muy popular que facilita la ejecución de aplicaciones NodeJS. PM2 facilita el reinicio de aplicaciones, reinicia automáticamente el bloqueo

Cómo crear una API RESTful de Node.js usando Express.js en Ubuntu 16.04 LTS

Cómo crear una API RESTful de Node.js usando Express.js en Ubuntu 16.04 LTS

En este tutorial, aprenderá cómo configurar una API RESTful completa, que atenderá las solicitudes HTTP utilizando Node.js y Express, mientras que el proxy inverso

Implemente una aplicación Node.js con Docker

Implemente una aplicación Node.js con Docker

Este artículo le mostrará cómo implementar su aplicación Node dentro de un contenedor Docker. Nota: Este tutorial asume que tienes Docker instalado y leído

Instalación de Node.js y Express en Ubuntu

Instalación de Node.js y Express en Ubuntu

Desarrollado por el motor Chrome V8, Node.js es un lenguaje popular utilizado para crear aplicaciones escalables rápidas. Ya ha impulsado numerosos proyectos, incluyendo

Desplegar Unikernels de Javascript a Vultr con Ops

Desplegar Unikernels de Javascript a Vultr con Ops

Despliegue de Unikernels de Javascript en Vultr Unikernels son sistemas operativos de aplicación única. A diferencia de los sistemas operativos de uso general como Linux, unikernel

Instalación de Ruby on Rails en Ubuntu 14.04

Instalación de Ruby on Rails en Ubuntu 14.04

Ruby on Rails (RoR) es un marco escrito en el lenguaje de programación Ruby que le permite usar Ruby en combinación con HTML, CSS y programas similares.

How to Install Strapi on Ubuntu 16.04

How to Install Strapi on Ubuntu 16.04

Introduction Strapi is an open source NodeJS Content Management Framework dedicated to build secure and scalable production-ready API applications an

Instalación de Node.js desde la fuente en Ubuntu 14.04

Instalación de Node.js desde la fuente en Ubuntu 14.04

Instalar herramientas de construcción Se necesitarán varias herramientas. Ejecute el siguiente comando: apt-get install make g ++ libssl-dev git Descargar Node.js source It i

Configurar Sails.js para desarrollo en CentOS 7

Configurar Sails.js para desarrollo en CentOS 7

¿Usando un sistema diferente? Introducción Sails.js es un marco MVC para Node.js, similar a Ruby on Rails. Hace para el desarrollo de aplicaciones modernas ver

Cómo configurar una aplicación de nodo Koa.js en Ubuntu 16.04 LTS

Cómo configurar una aplicación de nodo Koa.js en Ubuntu 16.04 LTS

En este tutorial, aprenderemos cómo configurar una aplicación web Koa.js para producción, utilizando Node.js. También vincularemos un dominio de muestra, con

Proxy inverso de Nginx con Ghost en Ubuntu 14.04

Proxy inverso de Nginx con Ghost en Ubuntu 14.04

Ghost es una plataforma de blogs gratuita y de código abierto escrita en node.js, completamente personalizable y dedicada a la publicación. Prepare el servidor: actualización

Configuración de un servidor web Express.js en Ubuntu 16.04 LTS

Configuración de un servidor web Express.js en Ubuntu 16.04 LTS

En este tutorial, instalaremos un servidor web básico Express.js, utilizando Node.js, un tiempo de ejecución de Javascript basado en el motor Chromes V8, en nuestro Vultr VP

Implementar una aplicación de meteorito en Ubuntu

Implementar una aplicación de meteorito en Ubuntu

Este artículo lo guiará a través de la implementación de su aplicación Meteor en un Vultr VPS con Ubuntu 14.04. También puede funcionar en otras distribuciones de Linux (intente un

Cómo instalar GruntJS en Debian 9

Cómo instalar GruntJS en Debian 9

GruntJS es un corredor de tareas de JavaScript escrito sobre NodeJS. Se puede utilizar para automatizar tareas repetitivas para su aplicación, como minificación, compilación

Cómo instalar NodeBB en CentOS 7

Cómo instalar NodeBB en CentOS 7

NodeBB es un software de foro moderno, de código abierto y basado en NodeJS. Con los clientes en mente, NodeBB ofrece a los propietarios de la comunidad funciones potentes y facilidad de uso t

Set up a Nuxt.js Web Application on Ubuntu 18.04 LTS

Set up a Nuxt.js Web Application on Ubuntu 18.04 LTS

Nuxt.js: The Universal Framework Nuxt.js is a JavaScript framework designed for quickly creating universal Vue.js applications. It is most famously notabl

Cómo implementar Ghost en Fedora 25

Cómo implementar Ghost en Fedora 25

¿Usando un sistema diferente? Ghost es una plataforma de blogs de código abierto que está ganando popularidad entre los desarrolladores y usuarios comunes desde su lanzamiento en 2013. yo

Cómo configurar aplicaciones persistentes de Node.js en Ubuntu 16.04

Cómo configurar aplicaciones persistentes de Node.js en Ubuntu 16.04

Las aplicaciones Node.js son populares por su capacidad de escalar. La ejecución de múltiples procesos concurrentes en múltiples servidores produce una menor latencia y un mayor tiempo de actividad

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.