top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

File System in Node.js

0 votes
695 views

In this article i will teach you how to access File System in node.js.

Using File System we can able to read and write file in node.js.For Accessing the File System we need to include the File System library.

In Node.js we use require command for importing the libraries.

For example,Now we need to include the file System library in node.js,so that we use the following command to include filesystem

var fs = require("fs")

Now we succesfully included the file system.

Using File System we can able to access the File I/O.

Some of the Functions comes under File System

fs.write(fd, buffer, offset, length, position, callback)
fs.writeSync(fd, buffer, offset, length, position)
fs.read(fd, buffer, offset, length, position, callback)
fs.readSync(fd, buffer, offset, length, position)
fs.readFile(filename, [options], callback)
fs.readFileSync(filename, [options])
fs.writeFile(filename, data, [options], callback)
fs.writeFileSync(filename, data, [options])

For all functions see the below official website link

http://nodejs.org/api/fs.html

Now we will see how to read file from synchronous and asynchronous way.

Read File in Node.js

I already mentioned in file system we can able to read file by synchronous way and also asynchronous way.

Next article i will clearly explain what is synchronous and asynchronous function.

Now we will go to see for how to read file .

First create one text file with contain some datas. File Name - > sample.txt- Inside Content -> This is the text file

Then Create a javascript file for accessing the read operation.

So i will create the file name as read.js

Then Write the below code for asynchronous function

var fs = require("fs");
console.log("Start Reading");
fs.readFile("sample.txt","utf8",function(error,data){
 console.log(data);
});
console.log("stoped");

Command for run the file in Ubuntu : node read.js

Output for the above program

start
stoped
This is the text file

Above function is a asynchronous function.The main aim of asynchronous is non-blocking.

See the same example for Synchronous function

 var fs = require("fs");
console.log("start");
var content = fs.readFileSync("sample.txt","utf8");
console.log(content);
console.log("stoped");

Output for above program

start
This is the text file
stoped

Synchronous method is a normal flow of execution.See more information about the file system in below link
http://nodejs.org/api/fs.html

Also the next article i will explain what is Synchronous and Asynchronous Function.

posted Aug 22, 2014 by Amarvansh

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

What is Web Server?

Web servers are computers that deliver (serves up) Web pages. Every Web server has an IP address and possibly a domain name.

How to create a web server in Node.js?

Using HTTP library will create a server.So first using require keyword will include the Http library.

Example:

var http = require("http");

Also you need host name and port number for creating the server.So set the Host Name and port number

Example:

var host = "127.0.0.1";
var port = "1337";

Creating a server
Server protocol will listen for host and port number.So next We can add the code to handle the requests, and to deliver a response.
Using createServer function will handle a request and response.This function will comes under http library.

Example :

var server = http.createServer(function(request,response){
response.writeHead(200,{"content-type":"text/plain"});
response.end("Hello World");
});

You can set the response text by using wirteHead method.

Then using listen function listen the host and port for the server

Example:

server.listen(host,port,function(){
console.log("Listening " + host + ":" + port );
});

So,Now you Successfully created the webserver.

See the Whole Example

var http = require("http");
console.log("Starting");
var host = "127.0.0.1";
var port = "1337";
var server = http.createServer(function(request,response){
console.log(request.url);
response.writeHead(200,{"content-type":"text/plain"});
response.end("Hello World");
});

server.listen(host,port,function(){
console.log("Listening " + host + ":" + port );
});

How to Run a server?

node server.js

Output for Above program
After running the program it will listen the host and port.Then in browser whenever reaches the host and port then it will receive the response

While Running It will Listening the port

Starting
Listening 127.0.0.1:1337

After reaching the port in browser the output will be

 Starting
 Listening 127.0.0.1:1337
 Received request:/

Then in browser it will display the Hello World.

READ MORE

Hi ,

In this article i will teach you what is synchronous and asynchronous function in the node.js

What is Synchronous Function?

When a synchronous function is called, it completes executing before returning control to the client application.

It means the synchronous function will execute step by step like one after the another.It wont give the executing control before current process got execute.

In Synchronous way It waits for each operation to complete, after that only it executes the next operation.

What is Asynchronous Function?

When an application calls an asynchronous method, it can simultaneously execute along with the execution of the asynchronous method that performs its task. An asynchronous method runs in a thread separate from the main application thread. The processing results are fetched through another call on another thread.

In Asynchronous way It never waits for each operation to complete, rather it executes all operations in the first GO only.

Now we will see how synchronous and asynchronous function in node.js.

First take one scenario for reading file operation in using Synchronous and Asynchronous Function.

In the last article i used some example for synchronous and asynchronous.So,we take the example and see how these functions will executing.

Now our aim is to create a node for reading file in both synchronous and asynchronous way

First create one text file with contain some datas insode. File Name - > sample.txt- Inside Content -> This is the text file

Then Create a javascript file for accessing the read operation.

So i will create the file name as read.js

Synchronous Function In Node.js

var fs = require("fs");
console.log("start");
var content = fs.readFileSync("sample.txt","utf8");
console.log(content);
console.log("stoped"); 

Above code is written by using synchronous way.I already told synchronous function is a normal flow of execution.It will one by one.It wont give the control to another process before it completes.

So let see how it is working.

Step 1 : Include the fs library for using File IO Operation
Step 2: we printed the Start message (So it will print start message)
Step 3 :Then using synchronous file operation(readFileSync) we read a file as synchronously and store result in a content variable.
Step 4: Then we will print the content variable and get the result.
Step 5: Finally we will print the Stopped message.

So in this function is step by step process.It make us to wait until the current process got completed.

Output for synchronous function:

start
This is the text file
stoped 

Asynchronous Function in node.js

var fs = require("fs");
console.log("Start Reading");
fs.readFile("sample.txt","utf8",function(error,data){
 console.log(data);
});
console.log("stoped"); 

Node.js is mainly for non-blocking.It means it will not wait for any thing.So in this asynchronous function will use to write a non blocking function.

Let see the above code how it is working in asynchronous way.

Step 1 : Include the fs library for using File IO Operation
Step 2: we printed the Start message (So it will print start message)
Step 3 :Then using asynchronous file operation(readFile) we read a file as asynchronously and write a callback function will show the data and as well show the error message if any error comes.
Step 4: Finally we will print the Stopped message.

So how it works It will not work like synchronous function

See first it will print the Start message
Next we reading a file.So,in asychronous funtion will not wait until the file read operation completes.It will Start executing the next level.
It means next it will print the Stop message.
Finally when the file reading work is done then it will print the file datas.

Output for the Asynchronous Function

start
stoped
This is the text file

Also see the Below video for more understating about synchronous Function and Asynchronous function
https://www.youtube.com/watch?v=Tu2zpGPzXxA

READ MORE

In this article I will tell you how to install node in Ubuntu,Windows and MAC and How to start.

Install Node.js in Ubuntu

sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

Above code will help you to install the latest version of the node.

using Git also can install nodejs

First install the dependencies

sudo apt-get install g++ curl libssl-dev apache2-utils
sudo apt-get install git-core

Then run the following commands

git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install

After installing you can check the version of nodejs by using the following command

node -v

Install nodejs in Windows

Install Node js using cygwin

What is cygwin?

Cygwin is free software that provides a Unix-like environment and software tool set to users of any modern x86 32-bit and 64-bit versions of MS-Windows

First,you need cygwin to install node in windows

To do so, follow these steps:

Step-1:Install cygwin.
Step-2:Use setup.exe in the cygwin folder to install the following packages:
Step-3 :

devel → openssl
devel → g++-gcc
devel → make
python → python
devel → git

Step-4:Open the cygwin command line with Start > Cygwin > Cygwin Bash Shell.

Then Run the below commands to download and build node.

git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install

Without using cygwin to install node.

Follow the below steps to install

1)Visit nodejs.org
2)Click the “install” button to download the installer.
3)Run the installer (make sure you tell the installer to add references to your PATH system variables).
4)Reboot your PC.
5)That’s it!You Successfully installed nodejs

How To check the version of nodejs in windows

1)Press Win + R (for Run)
2)Type: CMD
3)Click OK

Then in command prompt type the following command to see the version of nodejs

node --version

Install Node.Js in MAC

If you're using the excellent homebrew package manager, you can install node with one command:

brew install node

Otherwise, follow the below steps:

1)Install Xcode.
2)Install git.
Then run the following commands:

git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install

So,now installation node.js part is over.So next part is how to start node.js?

How to Start?

Simple Example for Hello Node

1)First Create one javascript file with the name of hellonode.js

2)Then enter the below code in that file

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Node.js\n');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');

3)Then open the command line(for windows),Terminal(For Ubuntu) and type follwing command to execute the First Simple Node Program

node hello_node.js

Output for the above Program

Server running at http://127.0.0.1:8124/
READ MORE

What is Node.js?

Node.js is a runtime environment and a library for running applications written in JavaScript outside the browser.

Node.js is a platform built on Chrome's JavaScript runtime for easily building fast, scalable network applications.

Node.js is an event based, asynchronous I/O framework that uses Google's V8 JavaScript Engine.

Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

It is used for developing applications that make heavy use of the ability to run JavaScript both on the client, as well as on server side and therefore benefit from the re-usability of code and the lack of context switching.

Some of the Applications that can be written using Node.js.

  • Static file servers
  • Web Application frameworks
  • Messaging middle ware
  • Servers for HTML5 multi player games

Normally it is an event-driven I/O framework for the V8 JavaScript engine.

Event-driven I/O server-side JavaScript environment based on V8

What is V8?

V8 is Google's open source JavaScript engine.

V8 is written in C++ and is used in Google Chrome, the open source browser from Google.

The basic philosophy of node.js is:

Non-blocking I/O - every I/O call must take a callback, whether it is to retrieve information from disk, network or another process.
Built-in support for the most important protocols (HTTP, DNS, TLS)
Low-level.
Do not remove functionality present at the POSIX layer. For example, support half-closed TCP connections.
Stream everything; never force the buffering of data.

Note:
Node.js is different from client-side Javascript in that it removes certain things, like DOM manipulation, and adds support for evented I/O, processes, streams, HTTP, SSL, DNS, string and buffer processing and C/C++ addons.

Video Tutorial for what is node.js?

https://www.youtube.com/watch?v=RH_BTidPkps

READ MORE

What is KeyStone.Js?
KeystoneJS is a powerful Node.js content management system and web app framework built on express and mongoose. Keystone makes it easy to create sophisticated web sites and apps, and comes with a beautiful auto-generated Admin UI.

KeystoneJS is the easiest way to build database-driven websites, applications and APIs in Node.js.

Features:

  • Express.js and MongoDB
  • Dynamic Routes
  • Database Fields
  • Auto-generated Admin UI
  • Simpler Code
  • Form Processing
  • Session Management
  • Email Sending

Keystone uses Mongoose, the leading ODM for node.js and MongoDB, and gives you a single place for your schema, validation rules and logic.

Keystone can configure Express for you, or you can take over and treat Keystone like any other Express middleware.

You can also easily integrate it into an existing Express app.

NPM Command
npm install -g generator-keystone

YO Generator
$ yo keystone

 

Video for KeyStone.JS

https://www.youtube.com/watch?v=DPXDFeUEk3g

READ MORE
...