A Quick Guide to Node.js Print

  • 0

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
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 tags will italicize the text. response.write("Hello, world! a + b = " + (a + b) + ""); // 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

Was this answer helpful?
Back

Powered by WHMCompleteSolution