How to Write Your First Node.js App in Linux

Web development trends have changed drastically over the last few years and as a web developer, to be at the top of your game, it’s important to stay updated with latest technologies.

JavaScript is the current trending programming language out there; it is without doubt the most popular technology used by full stack developers.

JavaScript web frameworks have become a magical solution to faster web development with absolute efficiency, safety and minimized costs. I am quite sure you have heard about Node JavaScript (commonly referred to as Node.js or simply Node), there is a buzz about it on the Internet.

In this article, I will show you how to get started with developing applications in JavaScript using Node.js in Linux. But first, lets get a brief introduction to Node.js.

What is Node.js?

Node.js is an open source, lightweight and efficient JavaScript runtime built on Chrome’s V8 JavaScript engine. It is designed without threads (single-threaded) and has a similar implementation to Twisted, a networking engine built using Python or Event Machine, an event-processing library for Ruby programs.

The heart of Node.js is based on event-driven programming; a programmer should therefore understand what events are available and how to respond to them.

Package Management Under Node.js

Node.js uses the JavaScript package manager and ecosystem called “npm”, which contains an immense collection of free open source libraries. It supports for modular software development. You can use it to install node packages, share, distribute your code and manage package dependencies.

Why is Node.js Important?

Node.js is a powerful and thus important because of the following reasons:

  • It uses an asynchronous event-driven, non-blocking I/O model of execution, which improves an application’s throughput and supports scalability for real-world web applications.
  • It is single threaded so it can only use 1 CPU at any given time.
  • A node.js web application is a complete web server for example Nginx or Apache.
  • It supports threads via the child_process.fork() API, for spawning child process, and also offers a cluster module.

With this brief introduction, you must be eager to write your first JavaScript program. However, first things first, you need to install Node.js and NPM packages on your Linux system using the following guide.

  1. Install Latest Nodejs and NPM Version in Linux Systems

How to Create Your First Node.js App in Linux

Once you have installed Node.js, you’re ready to go. First start by creating a directory that will store your application files.

$ sudo mkdir -p /var/www/myapp

Then move into that directory and create a package.json file for your application. This file helps as a small documentation for your project: name of project, author, list of packages it depends on and so on.

$ cd /var/www/myapp
$ npm init

This will ask you a number of questions, simply answer as described below, and press [Enter]. Note that the most important things in the package.json are the name and version fields as explained below.

  • package name – your app name, defaults to the directory name.
  • version – version of your app.
  • description – write a short description for your app.
  • entry point – sets the default packages file to be executed.
  • test command – used to create a test script (defaults to an empty script).
  • git repository – define a Git repository (if you have one).
  • keywords – set keywords, important for other users to identify your package on npm.
  • author – specifies author name, put your name here.
  • license – specify a license for your app/package.
Nodejs App Initialization
Nodejs App Initialization

Next, create a server.js file.

$ sudo vi server.js

Copy and paste the code below in it.

var http = require('http');
http.createServer(function(req,res){
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('Hello World!');
}).listen(3333);
console.log('Server started on localhost:3333; press Ctrl-C to terminate...!');

Next, start your application using following command.

$ node server.js
OR
$ npm start
Start Nodejs App Using NPM
Start Nodejs App Using NPM

Next, open a web browser and access your web app, which does nothing much other than print the string ”Hello world!”, using the address:

http://localhost:3333
Access Nodejs App from Browser
Access Nodejs App from Browser

In our code above, the main event that is being processed is an HTTP request via the HTTP module.

The Nodejs HTTP Module

In Node.js, modules are more like JavaScript libraries, they contain functions that you can reuse in your app. You can use in-built modules, thirty party modules or create your own.

To call modules in your app, use the require function as shown.

var http = require('http');

Once the http module is included, it will create a server that listens on a particular port (3333 in this example). The http.creatServer method creates the actual http server which accepts a function (which is invoked when a client tries to access the app) as an argument.

http.createServer(function(req,res){
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('Hello World!');
}).listen(3333);

The function in http.createServer has two arguments: req(request) and res(response). The req argument is the request from a user or client and the res argument sends a reply to the client.

res.writeHead(200, { 'Content-Type': 'text/plain' });		#This is a response HTTP header
res.end('Hello World!');

The final part of the code sends output to the console, once the server is launched.

console.log('Server started on localhost:3333; press Ctrl-C to terminate...!');

Routing in Node.js

In this section, I will explain one of the most important concepts under Node.js programming known as routing (comparable to routing under computer networking: process of finding a path for traffic in a network).

Here, routing is a technique of handling a client’s request; serving the content the client has requested for, as specified in the URL. A URL is made up of a path and query string.

To view a client’s request query string, we can add the lines below in our response.

res.write(req.url);
res.end()

Below is the new code.

var http = require('http');
http.createServer(function(req,res){
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.write(req.url);
      res.end();		
      }).listen(3333);
console.log('Server started on localhost:3333; press Ctrl-C to terminate...!');

Save the file and start your application again using following command.

$ node server.js
OR
$ npm start

From a web browser, type different URLs which will be displayed as shown below.

http://localhost:3333
http://localhost:3333/about
http://localhost:3333/tecmint/authors
View Your App Requests from Client
View Your App Requests from Client

Now, we will create a really small website for Tecmint with a homepage, about and authors pages. We will display some information on these pages.

Open the server.js file for editing, and add the code below in it.

//include http module 
var http = require('http');

http.createServer(function(req,res){
	//store URL in variable q_string

	var q_string = req.url;
	switch(q_string) {
		case '/':
                        	res.writeHead(200, { 'Content-Type': 'text/plain' });
                        	res.write('Welcome To Tecmint.com!')
                        	res.end();
                        	break;
                	case '/about':
                		res.writeHead(200, { 'Content-Type': 'text/plain' });
                        	res.write('About Us');
                        	res.write('\n\n');
                        	res.write('Tecmint.com - Best Linux HowTos on the Web.');
                        	res.write('\n');
                        	res.end('Find out more: https://www.tecmint.com/who-we-are/');
                        	break;
                	case '/tecmint/authors':
                        	res.writeHead(200, { 'Content-Type': 'text/plain' });
                        	res.write('Tecmint Authors');
                        	res.write('\n\n');
                        	res.end('Find all our authors here: https://www.tecmint.com/who-we-are/');
                        	break;
                	default:
                       		res.writeHead(404, { 'Content-Type': 'text/plain' });
                       		res.end('Not Found');
                        	break;
	}
}).listen(3333);
console.log('Server started on localhost:3333; press Ctrl-C to terminate....');

In the above code, we have seen how to write comments in Node.js using the // characters and also introduced switch and case statements for routing client requests.

Save the file, start the server and try accessing the various pages.

View Website Pages
View Website Pages

That’s it for now! You can find more information at Nodejs and NPM websites.

Read Also: How to Install PM2 to Run Node.js Apps on Linux

Conclusion

Node.js is rising to new highs today, it has made full-stack development much easier than before. It’s unique philosophy of event-driven programming enables you to create lightning fast, efficient and scalable web processes and servers.

Next, we will explain Node.js frameworks, which extend its native capabilities for quickly and reliably developing web/mobile applications. Do share your thoughts about this article via the comment section below.

Hey TecMint readers,

Exciting news! Every month, our top blog commenters will have the chance to win fantastic rewards, like free Linux eBooks such as RHCE, RHCSA, LFCS, Learn Linux, and Awk, each worth $20!

Learn more about the contest and stand a chance to win by sharing your thoughts below!

Aaron Kili
Aaron Kili is a Linux and F.O.S.S enthusiast, an upcoming Linux SysAdmin, web developer, and currently a content creator for TecMint who loves working with computers and strongly believes in sharing knowledge.

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

14 Comments

Leave a Reply
    • Look like the writer doesn’t do tech proofreading.

      In server.js he used port 8080 and then in the browser he is accessing via port 3333.

      Please do proofreading before posting.

      Thanks
      Numan Khan

      Reply
  1. Node.JS is basically used for writing code to build applications in JavaScript. The runtime environment includes software that allows programmers to write and edit code for future applications and run them. Node.JS is a server framework, which provides license-free technology. It is suitable for various platforms.

    Reply
  2. amazing tutorial for dummies (like me!) thanks a lot for this great explanation (i am not very good at English though)

    Reply
  3. Aaron thanks! It worked like a charm and was helpful for understanding node a bit more. Looking forward to the Frameworks How-to!

    Reply

Got Something to Say? Join the Discussion...

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.