Kode Blog - Inspiring And Empowering Developers.
We will start our Node.JS journey with a simple hello world application. Our application will not do much but will lay a solid foundation that will make it easy for us to learn Node.JS.
In this tutorial, we will create two simple hello world applications. One that displays the out in the console and the other that displays the information in the web browser.
We will cover the following topics in this tutorial;
For you to successfully complete this tutorial, you will need to know the following.
I am using windows operating system but you will still be able to follow the tutorial using any other operating system.
Open the command prompt and browse to drive C. feel free to use any drive of your choice
Run the following command to create a directory node. This directory will be used to store our applications
mkdir node
let’s now browse into the new directory using the following command
cd node
run the following command to create a directory for our application
mkdir hello-world
Run the following command to access the new directory hello-world
cd hello-world
Run the following command
npm init
Fill in the answers to the utility questions. Note: the utility always has sensible defaults. You just have to press the enter key to accept the default setting. You will however, need to enter the description, entry point and author name as shown below
The above command will create a package.json file in your project directory.
Open package.json
file.
You will get the following information
{
"name": "hello-world",
"version": "1.0.0",
"description": "A humble introduction to NodeJS app development",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Rodrick Kazembe",
"license": "ISC"
}
Let’s start with a very basic app.
Create a new file app.js
in the directory C:\node\hello-world\
Add the following code
console.log("Hello World!");
HERE,
console.log("Hello World!");
this line calls the log method of the console class. Console is a global module that provides simple debugging console that is similar to the one JavaScript console in web browsers. "Hello World!"
is the parameter that is passed to the log method.Let’s now run our application.
Go back to the console.
Browse to the application directory
Run the following command
node app.js
HERE,
node app.js
the node command executes the JavaScript file app.js
. Note: it is not necessary to specify the file extension. By default, Node.JS assumes the file extension is .js
. You can run the above command as node app
You will get the following results.
Hello World!
Congratulations. You just created your first nodejs application.
What if we want to accept some user input and display it in our hello message? How do we do that? We can use the global module process that contains information about the currently running Node.JS process
Add the following code to app.js
console.log();
console.log(process.argv);
HERE,
console.log();
prints a blank line console.log(process.argv);
displays an array of data that contains the command line arguments.Let’s now run our application in the console.
node app --name=Rodrick
You will get the following results
[ 'C:\\Program Files\\nodejs\\node.exe',
'C:\\node\\hello-world\\app',
'--name=Rodrick' ]
Note: we have the variable name with the value of Rodrick
Let’s now grab the command line argument and display it in the message that is returned to the user.
Replace the code for app.js
with the following
function getArgument(argument){
var index = process.argv.indexOf(variable);
return (index === -1) ? null : process.argv[index + 1];
}
var name = getArgument('--name');
var message = name ? "Hello " + name : "Hello World";
console.log(message);
HERE,
unction getArgument(argument){…}
defines a function that accepts the command line argument name. The function returns null if the argument name is not found, if the value if found, the function returns the value of the argumentvar name = getArgument('--name');
calls the getArgument function and passes in –name as the parameter. The result of the function is stored in the name variablevar message = name ? "Hello " + name : "Hello World";
assigns the message Hellow World to the message variable if the name is null. If it is not null then the message Hello name variable value is assigned to the message variable.console.log(message);
logs the information in the consoleLet’s now test our application.
Run the following command
node app
You will get the following results
Hello World
Let’s now specify the name argument
node app --name "Amanda Kazembe"
You will get the following results
Hello Amanda Kazembe
You can find more information about Node.JS API from the official documentation
https://nodejs.org/api/index.html
You can bookmark it for easy reference.
Let’s now create a simple web based hello world application. Let’s create a new file that we will name web.js
The web based application will involve the following steps.
Open web.js
file and add the following code
var http = require("http");
var port = 3000;
http.createServer(function(reqst, resp) {
resp.writeHead(200, {'Content-Type': 'text/plain'});
resp.end('Hello World!');
}).listen(port);
console.log('Load http://127.0.0.1:' + port + ' and watch the magic');
HERE,
var http = require("http");
require is used to import the http module. The web uses http that’s why we have to import this modulevar port = 3000;
defines a variable port and assigns a value of 3000 to it. This is the port number that the server will use.http.createServer(function(request, response) {…}
calls the createServer
method of the http
class and passes in an anonymous function as an argument. The anonymous function has two variables request
and response
. The request
variable contains information about the client request. The response
object is used to create the response that is sent back to the web browser.response.writeHead(200, {'Content-Type': 'text/plain'});
sets the HTTP status of 200
and a header Content-Type with a value of text/plain
.response.end('Hello World!');
sends the response hello World!
To the browserhttp.createServer(…).listen(port);
starts listening on the port specified by the value of the variable port. console.log('Load http://127.0.0.1:' + port + ' and watch the magic');
logs a message that shows the server URL that you can use to access the app from the browser.Load the following URL
http://127.0.0.1:3000/
You will get the following message in the browser
Hello World!
In this tutorial, we learnt how to create two simple basic Node.JS applications. Our applications didn’t do much but they give us an idea and feel of Node.JS applications.
The next tutorial is Node.JS Database MySQL. The tutorial will show you how to Node.JS application that can create, read and update and delete data from MySQL database.
If you found this tutorial useful, support us by using the social media buttons to like and share the tutorial. If you didn’t find it useful, please use the comments section below to let us know how we can do better next time.
Subscribe to our newsletter, like our Facebook fan page or follow us on Twitter to get free updates when we publish new tutorials
Tutorial version 1: Date Published 2016-08-02