Create a file using file system in node js. Perform  read, update,delete and rename functions on the file.

Here, we will write a program to create a file using file system in node js and perform various operations like read, update, delete and rename function on the file.

app.js file

var http=require('http');
var fs=require('fs');

var fs = require('fs');

http.createServer(function(req,res){
    // To create the file named sample.txt
    fs.open('sample.txt', 'w', function (err, file) {
        if (err) throw err;
        console.log('Saved!');
      });

    // To add text to the file
    fs.appendFile('sample.txt', ' This is a new text file.', function (err) {
        if (err) throw err;
        console.log('Updated!');
      }); 
    
    // To read the file named sample.txt
    fs.readFile('sample.txt',function(err,data){
        res.writeHead(200,{'Content-Type':'text/html'});
        res.write(data);   
        return res.end();
    })
    
    //To rename the file
    fs.rename('sample.txt', 'newSample.txt', function (err) {
        if (err) throw err;
        console.log('File Renamed!');
    });
    
    //To delete the file
    fs.unlink('newSample.txt', function (err) {
        if (err) throw err;
        console.log('File deleted!');
    });

}).listen(5007)