Create/Read/Write File using File Server: Node.js

Lets learn how to Create, read and write a file using file server module of Node.js

file-server-fs-create-read-write-file-nodejs

In this video tutorial we shall learn creating a folder/directory, creating a file, reading from a file, writing to a file and copying content from one file to another. We shall also see how you can look at all other facilities provided by fs module and make use of it in your real-time node.js web applications.

JavaScript: Reading a file
app.js

1
2
3
4
5
var fs= require("fs");
 
var html= fs.readFileSync("index.html", "UTF-8");
 
console.log(html);

Here we require fs module of node.js Using the readFileSync method of fs object, we open and read the file presented to it as its first argument. Second argument is the character-set type.

HTML FILE
index.html

1
2
3
<html>
<h1>Technotip.com</h1>
</html>

This is the html source code which will be fetched by app.js and being displayed on the console window upon execution.

JavaScript: Creating New File and Writing to file
app.js

1
2
3
4
var fs= require("fs");
 
var html= fs.readFileSync("index.html", "UTF-8");
fs.writeFileSync("satish.html", html);

Here we pass 2 arguments to writeFileSync method. First parameter being the file name – to be created, and the second parameter contains the content to be copied to the file we created.

JavaScript: Creating Directory/folder
app.js

1
2
3
4
5
var fs= require("fs");
 
fs.mkdir("satish");
 
console.log("Folder created!");

Pass name of the folder to be created to mkdir method of fs object.

JavaScript: Deleting a file
app.js

1
2
3
4
var fs= require("fs");
 
fs.unlink("satish.html");
console.log("File deleted");

Pass the existing file name to the unlink method and it’ll delete it. Make sure to give proper file name with correct file extension and path.

Create/Read/Write File using File Server: Node.js


[youtube https://www.youtube.com/watch?v=o7NIYGLC13o]

YouTube Link: https://www.youtube.com/watch?v=o7NIYGLC13o [Watch the Video In Full Screen.]



Note: There are plenty other file operation facilities provided by fs module, please use some other properties and methods from below list and let us know the code and what it does in the comment section below. This would surely help everyone in our reader community.

REPL of Node.js
Command Prompt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
C:\node>node
> fs = require("fs");
{ Stats: [Function],
  exists: [Function],
  existsSync: [Function],
  readFile: [Function],
  readFileSync: [Function],
  close: [Function],
  closeSync: [Function],
  open: [Function],
  openSync: [Function],
  read: [Function],
  readSync: [Function],
  write: [Function],
  writeSync: [Function],
  rename: [Function],
  renameSync: [Function],
  truncate: [Function],
  truncateSync: [Function],
  ftruncate: [Function],
  ftruncateSync: [Function],
  rmdir: [Function],
  rmdirSync: [Function],
  fdatasync: [Function],
  fdatasyncSync: [Function],
  fsync: [Function],
  fsyncSync: [Function],
  mkdir: [Function],
  mkdirSync: [Function],
  readdir: [Function],
  readdirSync: [Function],
  fstat: [Function],
  lstat: [Function],
  stat: [Function],
  fstatSync: [Function],
  lstatSync: [Function],
  statSync: [Function],
  readlink: [Function],
  readlinkSync: [Function],
  symlink: [Function],
  symlinkSync: [Function],
  link: [Function],
  linkSync: [Function],
  unlink: [Function],
  unlinkSync: [Function],
  fchmod: [Function],
  fchmodSync: [Function],
  chmod: [Function],
  chmodSync: [Function],
  fchown: [Function],
  fchownSync: [Function],
  chown: [Function],
  chownSync: [Function],
  _toUnixTimestamp: [Function: toUnixTimestamp],
  utimes: [Function],
  utimesSync: [Function],
  futimes: [Function],
  futimesSync: [Function],
  writeFile: [Function],
  writeFileSync: [Function],
  appendFile: [Function],
  appendFileSync: [Function],
  watch: [Function],
  watchFile: [Function],
  unwatchFile: [Function],
  realpathSync: [Function: realpathSync],
  realpath: [Function: realpath],
  createReadStream: [Function],
  ReadStream:
   { [Function: ReadStream]
     super_:
      { [Function: Readable]
        ReadableState: [Function: ReadableState],
        super_: [Object],
        _fromList: [Function: fromList] } },
  FileReadStream:
   { [Function: ReadStream]
     super_:
      { [Function: Readable]
        ReadableState: [Function: ReadableState],
        super_: [Object],
        _fromList: [Function: fromList] } },
  createWriteStream: [Function],
  WriteStream:
   { [Function: WriteStream]
     super_:
      { [Function: Writable]
        WritableState: [Function: WritableState],
        super_: [Object] } },
  FileWriteStream:
   { [Function: WriteStream]
     super_:
      { [Function: Writable]
        WritableState: [Function: WritableState],
        super_: [Object] } },
  SyncWriteStream:
   { [Function: SyncWriteStream]
     super_:
      { [Function: Stream]
        super_: [Object],
        Readable: [Object],
        Writable: [Object],
        Duplex: [Object],
        Transform: [Object],
        PassThrough: [Object],
        Stream: [Circular] } } }
>

Watch the above video to understand how to make use of above data in your own real-time node.js web application.

Adding Routes to Your Server: Node.js

With this video tutorial, lets learn about testing our code snippets using REPL, before implementing it into the actual node application. And then, we’ll show you how to add routes to your node server.

routes-node-server-request-response

In this tutorial, we create 5 routes to the server:
“/” to “Home Page”
“/about” to “About Us”
“/contact” to “Contact Us”
/”satish” redirected to “Home Page”
anything else to “Page Not Found”

Command Prompt
Console Window

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
C:\>node
> var url = require("url");
undefined
> var myURL = "http://Technotip.org:3030/about";
undefined
> url
{ parse: [Function: urlParse],
  resolve: [Function: urlResolve],
  resolveObject: [Function: urlResolveObject],
  format: [Function: urlFormat],
  Url: [Function: Url] }
> url.parse(myURL).hostname;
'technotip.org'
> url.parse(myURL).port;
'3030'
> url.parse(myURL).pathname;
'/about'
>

Here we test our code snippets on the command prompt, before implementing it into our actual application. Working with node url module on command prompt, we learnt to make use of parse() method of url object to fetch the hostname, port and the pathname of the actual URL. We are interested in pathname – we’ll be using it in our node application.

Related Read: Read Evaluate Print Loop (RELP): Node.js

JavaScript File
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
var url= require("url");
var http= require("http");
 
     http.createServer(function(req, res){
 
var pathname= url.parse(req.url).pathname;
 
if( pathname === '/' )
{
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Home Page");
}
else if( pathname === '/about' )
{
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("About Us");
}
else if( pathname === '/contact')
{
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Contact Us");
}
else if( pathname === '/satish' )
{
res.writeHead(301, { "Location": "/" });
res.end("Home Page");
}
else
{
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Page Not Found!!");
}
   }).listen("8080", "127.0.0.1");
 console.log("Server running ..");

Here we require url and http module. Using http object we create HTTP Server. Using url object we call parse method to parse and fetch the path from the user request URL.

Once we fetch the path, using conditional statements we display the corresponding message with appropriate response header information. We also illustrate 301 redirection

Adding Routes to Your Server: Node.js


[youtube https://www.youtube.com/watch?v=ejER-HVhDm8]

YouTube Link: https://www.youtube.com/watch?v=ejER-HVhDm8 [Watch the Video In Full Screen.]



Note: Make sure to turn on the server before trying to access the server!
execution code
command prompt

1
2
3
4
5
 
C:\>cd node
 
C:\node>node app.js
Server running ..

Navigate to the folder where you’ve your app.js file located, and run the server by executing the script using node command.

Read Evaluate Print Loop (REPL): Node.js

Today let us see REPL in Node.js

read-evaluate-print-loop-node-js

Most programming languages provide REPL facility to test and debug the code, and Node.js is no different in this approach.

Command Prompt
Console Window

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
C:\>node
> 1 + 1
2
> var a;
undefined
> a = 10
10
> a + 5
15
> a
10
> ++a
11
> a++
11
> a
12
> "Satish "+"B"
'Satish B'
> function technotip() { return 101; }
undefined
> technotip();
101
>2

Here we can type in our valid code snippet and instantly get the results. Some of the things we can do are: arithmetic operations, string manipulations, pre and post increment decrement of numbers, method declaration and defining and calling the methods etc.

We could even require some built-in node modules and using its objects we can look at the methods and properties it provides.
Command Prompt
Console Window

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
> var http = require("http");
undefined
> http.STATUS_CODES
{ '100': 'Continue',
  '101': 'Switching Protocols',
  '102': 'Processing',
  '200': 'OK',
  '201': 'Created',
  '202': 'Accepted',
  '203': 'Non-Authoritative Information',
  '204': 'No Content',
  '205': 'Reset Content',
  '206': 'Partial Content',
  '207': 'Multi-Status',
  '300': 'Multiple Choices',
  '301': 'Moved Permanently',
  '302': 'Moved Temporarily',
  '303': 'See Other',
  '304': 'Not Modified',
  '305': 'Use Proxy',
  '307': 'Temporary Redirect',
  '400': 'Bad Request',
  '401': 'Unauthorized',
  '402': 'Payment Required',
  '403': 'Forbidden',
  '404': 'Not Found',
  '405': 'Method Not Allowed',
  '406': 'Not Acceptable',
  '407': 'Proxy Authentication Required',
  '408': 'Request Time-out',
  '409': 'Conflict',
  '410': 'Gone',
  '411': 'Length Required',
  '412': 'Precondition Failed',
  '413': 'Request Entity Too Large',
  '414': 'Request-URI Too Large',
  '415': 'Unsupported Media Type',
  '416': 'Requested Range Not Satisfiable',
  '417': 'Expectation Failed',
  '418': 'I\'m a teapot',
  '422': 'Unprocessable Entity',
  '423': 'Locked',
  '424': 'Failed Dependency',
  '425': 'Unordered Collection',
  '426': 'Upgrade Required',
  '428': 'Precondition Required',
  '429': 'Too Many Requests',
  '431': 'Request Header Fields Too Large',
  '500': 'Internal Server Error',
  '501': 'Not Implemented',
  '502': 'Bad Gateway',
  '503': 'Service Unavailable',
  '504': 'Gateway Time-out',
  '505': 'HTTP Version Not Supported',
  '506': 'Variant Also Negotiates',
  '507': 'Insufficient Storage',
  '509': 'Bandwidth Limit Exceeded',
  '510': 'Not Extended',
  '511': 'Network Authentication Required' }

Here by using http object, we get all the status code supported by http module of node.js

Command Prompt
Console Window

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
> var os = require("os");
undefined
> os
{ endianness: [Function],
  hostname: [Function],
  loadavg: [Function],
  uptime: [Function],
  freemem: [Function],
  totalmem: [Function],
  cpus: [Function],
  type: [Function],
  release: [Function],
  networkInterfaces: [Function],
  arch: [Function],
  platform: [Function],
  tmpdir: [Function],
  tmpDir: [Function],
  getNetworkInterfaces: [Function: deprecated],
  EOL: '\r\n' }
> os.type
[Function]
> os.type();
'Windows_NT'

Here we see contents of os module. Also fetch the type of Operating System we are using, by using type() method supported by OS module.

Read Evaluate Print Loop (REPL): Node.js


[youtube https://www.youtube.com/watch?v=F2tYaJADVos]

YouTube Link: https://www.youtube.com/watch?v=F2tYaJADVos [Watch the Video In Full Screen.]



Note: Node.js is built on the same Google’s V8 JavaScript Engine which is using by Google’s Chrome – thus providing the same speed and robustness to our node.js applications.

For quick reference: Status Code and it’s meaning
‘100’: ‘Continue’,
‘101’: ‘Switching Protocols’,
‘102’: ‘Processing’,
‘200’: ‘OK’,
‘201’: ‘Created’,
‘202’: ‘Accepted’,
‘203’: ‘Non-Authoritative Information’,
‘204’: ‘No Content’,
‘205’: ‘Reset Content’,
‘206’: ‘Partial Content’,
‘207’: ‘Multi-Status’,
‘300’: ‘Multiple Choices’,
‘301’: ‘Moved Permanently’,
‘302’: ‘Moved Temporarily’,
‘303’: ‘See Other’,
‘304’: ‘Not Modified’,
‘305’: ‘Use Proxy’,
‘307’: ‘Temporary Redirect’,
‘400’: ‘Bad Request’,
‘401’: ‘Unauthorized’,
‘402’: ‘Payment Required’,
‘403’: ‘Forbidden’,
‘404’: ‘Not Found’,
‘405’: ‘Method Not Allowed’,
‘406’: ‘Not Acceptable’,
‘407’: ‘Proxy Authentication Required’,
‘408’: ‘Request Time-out’,
‘409’: ‘Conflict’,
‘410’: ‘Gone’,
‘411’: ‘Length Required’,
‘412’: ‘Precondition Failed’,
‘413’: ‘Request Entity Too Large’,
‘414’: ‘Request-URI Too Large’,
‘415’: ‘Unsupported Media Type’,
‘416’: ‘Requested Range Not Satisfiable’,
‘417’: ‘Expectation Failed’,
‘418’: ‘I\’m a teapot’,
‘422’: ‘Unprocessable Entity’,
‘423’: ‘Locked’,
‘424’: ‘Failed Dependency’,
‘425’: ‘Unordered Collection’,
‘426’: ‘Upgrade Required’,
‘428’: ‘Precondition Required’,
‘429’: ‘Too Many Requests’,
‘431’: ‘Request Header Fields Too Large’,
‘500’: ‘Internal Server Error’,
‘501’: ‘Not Implemented’,
‘502’: ‘Bad Gateway’,
‘503’: ‘Service Unavailable’,
‘504’: ‘Gateway Time-out’,
‘505’: ‘HTTP Version Not Supported’,
‘506’: ‘Variant Also Negotiates’,
‘507’: ‘Insufficient Storage’,
‘509’: ‘Bandwidth Limit Exceeded’,
‘510’: ‘Not Extended’,
‘511’: ‘Network Authentication Required’

URL Redirection Using Node.js

Lets learn how to redirect with a 301 status code – which means “moved permanently”, using Node.js

301-redirection

Related Read: HTTP Server(request/response): Node.js

Here we’re passing 301 redirect status code with redirection location URL in the header information to the client – the browser.

JavaScript File
app.js

1
2
3
4
5
6
7
8
9
10
var http= require("http");
 
     http.createServer(function(req, res){
     res.writeHead(301, {
 "location" : "http://technotip.org"
 });
 res.end();
   }).listen(3030, "127.0.0.1");
 
 console.log("server redirects from localhost to technotip.org");

We require/include http module of node.js We call createServer() method of http object and this method passes 2 objects to the callback methodrequest and response objects. Using request object we call writeHead() method and pass 301 status code and the redirect location information. After this, we indicate the end of the process by calling end() method.

Also we assign the port 3030 at 127.0.0.1 for the client access of this server.

Now visit localhost:3030 or 127.0.0.1:300 and you’ll be redirected to http://technotip.org

301 Redirection Using Node.js


[youtube https://www.youtube.com/watch?v=neIeFVMsuJY]

YouTube Link: https://www.youtube.com/watch?v=neIeFVMsuJY [Watch the Video In Full Screen.]



Status Code Definitions

Informational 1xx
100 Continue
101 Switching Protocols

Successful 2xx
200 OK
201 Created
202 Accepted
203 Non-Authoritative Information
204 No Content
205 Reset Content
206 Partial Content

Redirection 3xx
300 Multiple Choices
301 Moved Permanently
302 Found
303 See Other
304 Not Modified
305 Use Proxy
306 (Unused)
307 Temporary Redirect

Client Error 4xx
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Request Entity Too Large
414 Request-URI Too Long
415 Unsupported Media Type
416 Requested Range Not Satisfiable
417 Expectation Failed

Server Error 5xx
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported

Network I/O Is Unpredictable: Node.js

We’ve seen the importance of callback method in our previous video tutorials. Now lets see how networked I/O Is unpredictable.


http-module-get-method-nodejs-network-io-unpredictability

Here we request/ping for information from 3 different servers and look at its response time. Each time we send a request, we get different response time depending upon how busy the server is, its bandwidth etc.

JavaScript File
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var http= require("http"),
      urls  = [ "technotip.org",
         "technotip.com",
      "www.capturecaption.com"
       ];
 
for(var i = 0; i < urls.length; i++){
ping( urls[i] );
}
 
function ping( url ){
var start = new Date();
 
http.get({ host: url }, function(res){
console.log("URL :"+url);
console.log("Response Time: "+(new Date() - start)+" ms");
});
}

Here we require http module, which is built into nodejs, and store it inside a local object called http. We also declare and initialize an array with 3 domain names. Using for loop, we loop through each URL present in the urls array and pass it to a method called ping();

Inside ping method, we record client system date in a variable before sending a request to the server(via URL). Now using http objects get method we send request to the server and see it’s response time. get method takes 2 parameter, first parameter is an object which contains host information – the host url { host: url }. Second parameter is a callback method which automatically gets an object which is returned by first parameter {host: url}. Inside the callback method, we subtract the new system date with the one we recorded before requesting for a response, this way we calculate the response time of each URL.

HTTP get method: Node.js


[youtube https://www.youtube.com/watch?v=vktKMtWoPbA]

YouTube Link: https://www.youtube.com/watch?v=vktKMtWoPbA [Watch the Video In Full Screen.]



output
C:\node>node app.js
URL :technotip.com
Response Time: 1462 ms
URL :www.capturecaption.com
Response Time: 1993 ms
URL :technotip.org
Response Time: 2004 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1381 ms
URL :www.capturecaption.com
Response Time: 1702 ms
URL :technotip.org
Response Time: 1871 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1409 ms
URL :www.capturecaption.com
Response Time: 1628 ms
URL :technotip.org
Response Time: 2001 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1512 ms
URL :www.capturecaption.com
Response Time: 1534 ms
URL :technotip.org
Response Time: 1899 ms

Each time we execute the script, we get different response time, and the order of URLs may also differ, as we can’t predict which server will respond first.