Press "Enter" to skip to content

NodeJS web server to test your scripts on Ubuntu

The content of the article adheres to our principles of editorial ethics. To report an error click here.

Get started with NodeJS on Ubuntu

NodeJS is an open-source server side framework built on JavaScript under MIT (Massachusetts Institute of Technology) license. It is mainly used for asynchronous programming and it is a very light weight framework that makes it faster than other frameworks. It is also supported by most of the popular operating systems. Different types of applications like web application, command line application, RESTful API etc. can be developed with this framework. How you can easily install and use this framework on Ubuntu are shown in this article.

NodeJS Installation Steps

1. Press Ctrl+Alt+T to open the terminal and run the following command to install NodeJS

$ sudo apt-get install -y nodejs

After completing the installation process, type the following command to check the version of the installed framework.

2. To install necessary modules and packages you will need to install NodeJS package manager called npm. Run the following commands to install the npm.

$ sudo npm install npm –global

Check the version of npm.

Now, NodeJS is ready to use for developing any application. How you can apply NodeJS as a beginner is shown in the next part of this article.

Using NodeJS

You can use NodeJS for various types of application development. As a beginner, how you can create a simple console application and a web server are shown in this part.

Creating Console application

Run the following commands to create a directory named nodejsapp for keeping your code organized, go to the newly created directory and open the nano editor for creating a JavaScript file named firstapp.js.

$ mkdir nodejsapp
$ cd nodejsapp
$ nano firstapp. js

Write the following code in the file to print a output in the console. Press Ctrl+x and then y to save the file and exit from the editor.

console. log ( ‘First NodeJS Application’ ) ;

Run the following command to execute the code of the firstapp.js file.

$ nodejs firstapp. js

if you get any permission problem to execute the script then you have to run the following command for setting execution permission of firstapp.js file and again run the above command.

$ chmod + x firstapp. js

Creating Local Web Server

JavaScript is a popular client side scripting language which doesn’t require any web server to run. Web server is required to run any server side scripting language like php, asp etc. and you need to install a particular web server to run server side scripts. Using NodeJS framework, you can easily implement a local web server which can be used to run server side script.

Open nano editor to create a new JavaScript file named server.js that will be used to create a local web server.

$ nano server. js

Add the following code in the file to create the server connection on port number 6060. According to this code, NodeJS will listen for server connection at localhost:6060 and if the connection can be established successfully then 200 code will be generated and ‘NodeJS App’ will be shown as output.

var http = require ( ‘http’ ) ;

var server = http. createServer ( function ( request response ) {
resquest. writeHead ( 200 , { ‘Content-Type’ : ‘text/plain’ } ) ;
response. end ( ‘NodeJS App’ ) ;
} ) ;
server. listen ( 6060 ) ;
console. log ( ‘Server is running at http://localhost:6060/’ ) ;

Save the file by pressing Ctrl+x and y. Now, execute the following command to run the web server. If the code executes properly then the message ‘Server is running at http://localhost:6060’ will be displayed in the console.

$ nodejs server. js

Open any browser to check the web server code is working properly or not. The script will return ‘NodeJS App’as content in the browser if the above code executes properly. Type the following URL in the address bar for checking.

In the above example, a simple static text is displayed in the browser which is added as the content with response. But generally, any index file displays when the base URL executes. So, how you can attach any html file in the server connection script is shown in the next part.

At first, create a very simple html file named index.html using Text Editor with the following code and save it in the nodejsapp directory which is created previously.

Now, create another JavaScript file named server2.js with the following code to view index.html file, after creating web server connection. Here, fs module is used to read the index.html file. Three types of outputs can be generated based on the code. If the connection establishes properly and index.html file exists then it will load the content of index.html file in the browser. If the connection establishes but index.html file does not exist on the current location then ‘Page is not found’ message will print. If the connection establishes and index.html file also exists but requested url is not correct then ‘Default content’ text will display as by default content. Port number 5000 is set as listening port here. So when web server connection establishes successfully then the message ‘Server is listening on 5000’ will show in the console.

var http = require ( ‘http’ ) ;
var fs = require ( ‘fs’ ) ;

var server = http. createServer ( function ( request, response ) {

if ( request. url === “/” ) {
fs. readFile ( “index.html” , function ( error, pgResp ) {
if ( error ) {
response. writeHead ( 404 ) ;
response. write ( ‘Page is not found’ ) ;
} else {
response. writeHead ( 200 , { ‘Content-Type’ : ‘text/html’ } ) ;
response. write ( pgResp ) ;
}

response. end ( ) ;
} ) ;
} else {

response. writeHead ( 200 , { ‘Content-Type’ : ‘text/html’ } ) ;
response. write ( ‘

Default Content

‘ ) ;
response. end ( ) ;
}
} ) ;

server. listen ( 5000 ) ;

console. log ( ‘Server is listening on 5000’ ) ;

Save the file and exit from the editor. Run the server by executing the following command.

$ nodejs server2. js

Type the following URL to view the content of index.html file in the browser.

Now, insert an invalid URL in the browser and check the output.

Now modify server2.js file and set the file name as index2.html that does not exit and restart the server. Type the base URL again to check the output.

NodeJS is a demanding framework and you can perform many tasks using it. As a beginner, you can follow the steps which are shown in this article to start application development using NodeJS.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

NodeJS web server to test your scripts on Ubuntu

In the next article we are going to take a look at how we can create a NodeJS web server. With it we can test our own scripts locally. Developing applications with this framework is quite simple, and we can create from simple console applications to a web server, which will be the subject of this article.

Who wouldn’t take a look at the article about NodeJS that was already published in this same blog a while ago, to say that this is a JavaScript-based open source server framework. It is mainly used for asynchronous programming and it is a very lightweight framework that makes it faster than others. It is also compatible with most popular operating systems. Different types of applications, such as web applications, command line applications, etc. they can be developed with this framework using Ubuntu (or other OS).

Table of Contents

  • 1 Create a local NodeJs web server
    • 1.1 NodeJs web server displaying static text
    • 2.1 HTML file for our server
    • 2.2 Server configuration
    • 2.3 Testing the NodeJs web server

    Create a local NodeJs web server

    NodeJs web server displaying static text

    Using this framework we will be able to easily implement a local NodeJs web server. We can use this to run server-side scripts without complications.

    To begin we will only have to open the nano editor in the terminal (Ctrl + Alt + T) to create a new JavaScript file called server.js which we will use to create the local NodeJs web server.

    nano server.js

    Once open, we will add the following code in the file to create server connection using port 6060. According to this code. NodeJS will listen for the server connection in localhost: 6060. If the connection can be established successfully the NodeJS application will output a basic text (in this case).

    var http = require('http'); var server = http.createServer(function(req, res) < res.writeHead(200,); res.end('NodeJS App'); >); server.listen(6060); console.log('El servidor está funcionando en http://localhost:6060/');

    Once the code is copied, we have to save the file. We will execute the following command to launch the web server. If the code runs successfully, the message ‘The server is running at http: // localhost: 6060‘in the console:

    nodejs server.js

    We will be able to open any browser to verify that the web server code is working correctly or not. The script will return the text ‘NodeJS App‘as content in the browser if the above code executes correctly. Type the following URL in the address bar to verify:

    http://localhost:6060

    In the example above, a simple static text in browser. But generally any file is displayed when the base url is executed.

    Attach html file to our NodeJs web server

    On this server you can attach any html file. This is included in the server connection script. We will see an example of this below.

    HTML file for our server

    To begin with, we are going to create a very simple html file named index.html using a text editor. In it we will include the following code and we will save it.

       Probando NodeJS  

    Probando el servidor con NodeJS

    Esta es mi primera aplicación con NodeJS creada como ejemplo

    Server configuration

    Once the above file is saved, we will create another JavaScript file called server2.js with the following code to view the file index.html. We will save these two files in the same folder, for higher comfort.

    var http = require('http'); var fs = require('fs'); var server = http.createServer(function (req, res) < if (req.url === "/") < fs.readFile("index.html", ‘utf8’, function (error, pgResp) < if (error) < res.writeHead(404); res.write('Página no encontrada'); >else < res.writeHead(200, ); res.write(pgResp); > res.end(); >); > else < res.writeHead(200, < 'Content-Type': 'text/html' >); res.write('

    Contenido por defecto

    '); res.end(); > >); server.listen(5000); console.log('El servidor está escuchando en el puerto 5000');

    The fs module is used to read the index.html file. The above code can generate three types of outputs. If the connection is successful and index.html exists, its content will be loaded into the browser. In case the connection is established but the index.html file does not exist, the message ‘Page not found‘. If the connection is established and the index.html file also exists, but the requested URL is not correct, the text ‘Default content‘will be displayed as the default content.

    When the connection to the web server is successfully established, the message «The server is listening on port 5000«.

    Testing the NodeJs web server

    To run the server we will write the following command:

    nodejs server2.js

    Enter the following URL to view the contents of the index.html file in the browser:

    http://localhost:5000

    Now let’s try enter invalid url in browser and check the output.

    http://localhost:5000/test

    If we modify the server2.js file and we change the file name to index2.html and we relaunch the server, we will see the error of “Page not found”.

    NodeJS is a good framework with which you can do many things. Any user can follow the steps shown in this article to get started in application development using NodeJS.

    The content of the article adheres to our principles of editorial ethics. To report an error click here.

    Full path to article: ubunlog » Ubuntu » NodeJS web server to test your scripts on Ubuntu

Comments are closed, but trackbacks and pingbacks are open.