How to Set Up a Node.js Application On Ubuntu 16.04 VPS

How to Set Up a Node.js Application On Ubuntu 16.04 VPS

Node.js is an open source, cross platform, server side environment for building fast and scalable network applications. Node.js applications are written in JavaScript and executed by Google’s V8 JS engine. It effectively allows you to run JavaScript code on the server. Here are some of its main features:

  • Completely Asynchronous: all calls in Node.js are asynchronous, and thus do not block execution. This is achieved using Events and Promises, patterns native to the JavaScript language.
  • Single threaded: Node.js works only on a single thread, which fits well into its event driven architecture. Node.js applications are fast and scalable because they never buffer data.
  • Freely licensed: Node.js is released under the MIT license, so you can do almost anything with its source code.

If you need CPU intensive computations, Node.js may not be the right choice for you. It is severely limited by its use of only one thread, and you should probably use C++ or Python instead. Here is what kind of apps Node.js is the right fit for:

  • Web applications
  • I/O bound apps
  • API services

The list of companies that use it speaks volumes about its usefulness: PayPal, Netflix, Ebay, Walmart, Medium.com, Mozilla, NASA, Linkedin, Trello… You will also find thousands of individual projects written in Node.js as well.

What we are going to cover

  • installation of latest Node.js,
  • what is REPL and how to use it,
  • what are NPM packages and how to benefit from them,
  • creation of an example web app in Node.js

Prerequisites

  • A clean VPS with root access,
  • running Ubuntu 16.04 with
  • at least 512MB RAM, 1GHz CPU and 20Gb disk space.
  • Understanding of JavaScript.

Step 1: Install the Latest Node.js

First, login to your VPS as root via SSH. Navigate to the /tmp directory by running the following command:

cd /tmp

Install curl:

apt install curl -y

Download the installation script for the latest NodeJS version:

curl -sLO https://deb.nodesource.com/setup_12.x

At the time of writing of this article, the latest Node.js version was v12. New versions are being released in April and October. To install a newer version, substitute the new version number in the command above.

Run it with:

bash setup_12.x

The script will set up the proper Ubuntu package repositories. It will take a while to run. When it finishes, install Node JS and compilation tools by running:

apt install -y nodejs gcc g++ make

You have also installed gcc, g++ and make. They may be required by some Node.js packages during their installation to compile their parts written in C or C++. You’ll learn about Node.js packages later in the tutorial.

When the installation finishes, run the following command to inspect Node.js version:

nodejs -v

If it shows a version (which was, at the time of writing, v12.2.0), you have installed Node.js correctly. If it shows an error, double check the commands you entered against the ones shown above.

Step 2: Learning About Node.js REPL

REPL stands for Read-Eval-Process-Loop and is an interactive environment for Node.js. You execute a single expression and the result is printed back immediately. It is a great way to experiment with the language.

Run the integrated Node.js REPL with the following command:

nodejs

You’ll see the following:

Welcome to Node.js v12.2.0.
Type ".help" for more information.
>

The REPL now waits for you to enter an expression. Try some simple math by typing in:

1+2

The result will be 3. Parentheses are also obeyed:

(1+2)*5

You can now try executing some of Node’s built-in functions, such as printing to console:

console.log('hello!')

The output will be:

hello!
undefined

The REPL executed the console.log() call, which returned ‘hello!’. undefined, shown in gray in the next line, means that the call did not return anything.

Variables are also supported:

a=5
b=6

You can try adding them:

a+b

The result will be 11, shown in yellow, which denotes a number. (Green denotes a string.)

You can use the up and down arrows to traverse through command history. To list all the available commands, press Tab twice.

To exit the Node.js REPL, press CTRL + C twice.

Step 3: Learning About NPM Packages

NPM (Node Package Manager) is the world’s largest JavaScript library registry with package manager capabilities. Both open source developers and big companies use it to make software development easier. NPM is free to use and is included with Node.js since version 0.6.3.

The biggest benefit of NPM is its package manager. You specify all your project dependencies in a file named package.json, and all you need to do to start developing is run npm install. It is also possible to specify specific versions of packages that your project will work with.

Confirm that npm is installed and check its version by running:

npm -v

Local and Global Package Installations

With NPM, installing packages is easy. To install a package locally, just run:

npm install 

and NPM will take care of all the dependencies for you. Installing a package locally means that NPM will download and store the files in a directory named nodemodules_ in the current directory.

For example, if you wish to locally install cheerio (a version of jQuery optimized for server side), you’ll need to run:

npm install cheerio

When cheerio finishes installing, you can import it from your code with this line:

const cheerio = require('cheerio');

The cheerio object will provide access to the library’s functionality.

By passing ‘-g’ to npm install, you can install packages globally. You can access them from the CLI, but can’t import them from the code. To list all the globally installed packages, run:

npm ls -g

Updating, Uninstalling, Searching

To update a package, use npm update:

npm update 

To uninstall a package, use npm uninstall:

npm uninstall 

You can also search for a package by its name using npm search:

npm search 

You will get a tabulated list of packages whose name matches the one you passed in.

Creating a New Package

File package.json stores information about the package. Creating a package.json makes sense only when you want to publish your library to the npm package registry.

From the working directory of your package, run the following command to create one interactively:

npm init

It will ask you for your package name, current version, description, entry point file, command for running tests, Git repository, keywords, your name as the author and code license. NPM will then ask you if you are content with the generated JSON – if you are, type in ‘y’ or press Enter.

NPM will then save the newly generated package.json into the current directory.

Publishing a Package

To publish a package to the NPM package registry, first sign up for an account at npmjs.org.

If you haven’t logged in before already, NPM will have you log in before you publish a package. You can add a new user to npm with the following command:

npm adduser

NPM will then ask you for your username, password and email address (which will be shown publicly). When you are done, you can publish your package by running the following command from the working directory of your package:

npm publish

Step 4: Creating an Example Web Server App

We’ll now create a simple web server app which will return the requested URL in upper case. To create an HTTP server, we’ll use the built-in http package, and to convert characters to their upper case variants, we’ll use the upper-case package from NPM. Install the latter using this command:

npm install upper-case

Navigate to the home directory:

cd ~

Open a file named uppercase-http.js for editing:

nano uppercase-http.js

Add the following lines:

var http = require('http');
var uc = require('upper-case');
console.log('starting...');
http.createServer(function (req, res) {
  console.log('received request for url: ' + req.url);
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write(uc(req.url + 'n'));
  res.end();
}).listen(8080);

Save and close the file.

First, we require two packages (http and upper-case) and store them in separate variables (http and uc, respectively). Then we call the createServer method of the http package and pass it a function which will be executed whenever the server receives a request; the request itself will be stored in variable req.

The function will write the Content-Type header of type text/html to the response variable res, telling the client that the response will be in HTML. In line starting with res.write(), we call uc (the upper-case package), which will return the uppercase variant of the requested URL and append a new line to it.

The last two lines end the response by calling end() and order the HTTP server to listen to port 8080. You can specify any other port that you like, provided that it will be free when the app runs.

Run the app:

node uppercase-http.js

You will see the following message:

starting...

To test it, fire up another terminal, connect to your VPS as root via SSH and curl localhost:8080:

curl localhost:8080

The output will be a slash (/), because you haven’t requested a more specific path. Try curl-ing /hello:

curl localhost:8080/hello

You’ll get the following response:

/HELLO

The program correctly converted the path to uppercase. If you look at the server app itself, it showed a status message for both requests:

received request for url: /
received request for url: /hello

If you’d like to access this app from your web browser, you’d need to configure a reverse proxy (probably using Nginx), which is out of scope of this tutorial.

Conclusion

Now that you know how to install Node.js and use NPM, you’ll be able to craft hobby projects over the weekend, or try building the next Netflix! Node.js is flexible enough to run on even the cheapest servers, and you’ll still be able to build a professional web app with it.

Dusko Savic is a technical writer and Flutter programmer.

DuskoSavic.com

The post How to Set Up a Node.js Application On Ubuntu 16.04 VPS appeared first on Low End Box.