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:
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:
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.
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.
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.
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
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
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.
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.
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
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.
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.
The post How to Set Up a Node.js Application On Ubuntu 16.04 VPS appeared first on Low End Box.
In this article, we will see how to Install Google Cloud BigQuery Python client library…
Nov 15,2024 Wallpaper Contest for Xfce 4.20 open for voting The submission phase for the…
MicroCloud 2.1.0 LTS is now available, expanding the number of Canonical infrastructure solutions with a…
Canonical is thrilled to be joining forces with Dell Technologies at the upcoming Dell Technologies…
In today’s massive private mobile network (PMN) market, one of the most common approaches to…
Welcome to the Ubuntu Weekly Newsletter, Issue 865 for the week of November 3 –…