Monday, March 12, 2018

NodeJS Basics I

Hello Everyone,
By this post you will be able to understand the basic stuff about NodeJS.
Firstly I will introduce what NodeJS is,

Node.js is a very powerful JavaScript-based framework.Platform was built on Google Chrome's JavaScript V8 Engine. Node.js is a server side scripting language which is mostly used for back end of the application.

In order to see whether node.js is successfully installed in your machine, use the following commands.




Basic Hello World Program


Using the require directive I have used the http module and returned an instance of it.Instance of server is created from createServer method and in the body 'Hello World' is printed.By using listen keyword, we define that server runs on that port number and output will be available in that port number.After connection is successfully established, console log statement will be executed in the console.

In order to run the node.js file, first open a terminal in the directory where your js file exists.




Output to the console

Reading a File

Now Let's look at some of the capabilities node.js has. It has the ability to read files in either synchronous way or asynchronous way.When both forms are present, node.js tends to read in the synchronous way first.



To read files node file system module is required.It is represented as fs in node.js. In here read.txt is an external file which contains some content which is read by node application. Below is the read.txt file.



Asynchronous reading takes callback function with 2 parameters err and data.First parameter is used to represent any errors that can occur while reading and data parameter is used to state the completion of the function.
In synchronous reading readFileSync keyword is used where no callback functions is used.In general Asynchronous reading is more approprite than synchronous reading where no blocks can occur in the reading process.


Output to the console




Writing a File

In here we over write the existing file using writeFile method.First parameter is said to be the file name where we want to write the content and second parameter is the content that we want to write to the file and at third we use call function with err as the parameter to display any errors that can occur during writing.




Output to the console







Let's meet again with another exiting post.Happy coding :)

©Copyright Viraj Wickramasinghe.

No comments:

Post a Comment