Learn Node.js

Node.js File System

Node.js file system module allow us to work with file.To include file system using following syntax.

var files = require("fs");

We can do following Task with File System module.

  • Reading file
  • Creating file
  • Updating file
  • Deleting file
  • Renaming file

Reading file

The files.readFile() method is used to read files on your computer.

Assume we have the following HTML file located in the same folder.

<h1>Hi to all.</h1>

Now we will create a Node.js file (read.js) that reads the HTML file, and return the content to browser.

var http = require('http');
var file = require('fs');
http.createServer(function (req, res) {
  file.readFile('read.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});

If you will run above Node.js file,you will see the html data as output.

Creating file

The File System module has following methods for creating new file.

  • fs.appendFile()
  • fs.open()
  • fs.writeFile()

The fs.appendFile()