How to Work with Files in Node.js

How to Work with Files in Node.js

ยท

2 min read

Node js, fs module allows us to work with the file system. In a file system, there are several operations that we can do by the fs module

This is a beginner-friendly Article here we explore some of the functions of the module.

Common use for the File System module:

  • Read files

  • Create files

  • Update files

  • Delete files

  • Rename files

How to Read Files๐Ÿ˜€

Let's create a demo html file where we do these operations.

I am creating a demo.HTML file

To read the files directly from your computer, you'll have to use the use the fs.readFile() method.

Let's code ๐Ÿค—

First, create a server with a node. js I am creating this server in fs.js file

You can also use Express to create a simple server.

For using the function we require the fs module

const http = require('http');   // for server
const fs = require('fs');

http.createServer((req,resp)=>{
    fs.readFile('demo.html',(err,data)=>{
       resp.writeHead(200,{'Content-Type':'text/html'});

       resp.write(data);
       return resp.end();
    });
}).listen(5000,()=>{
    console.log('Server is runing ')
});

Output

How to Create Files

The fs.appendFile() method appends specified content to a file. If the file does not exist, the file will be created:

fs.appendFile('demo_file.txt','I Love Node',(err)=>{
    if(err) throw err;
    console.log('data is saved')
})

Output

if you don't want to write anything in the file and create an empty file you just leave the second parameter('I Love Node') by (' ')

How to Update Files๐Ÿซก

fs.appendFile('demo_file.txt','I am updated text',(err)=>{
    if(err) throw err
    console.log('File is updated');
})

Output

How to Delete Files๐Ÿง

To delete a file we'll have to call the unlink method.

fs.unlink('update_name_demo_file.txt',(err)=>{
    if(err)throw err

    console.log("File is deleted");
})

Output

This rad line indicates that update_name_demo_file.txt is deleted.

How to Rename Files

Another major part of working with files is renaming an already existing file. Let's take a look at how that works:fs.rename() method.

fs.rename('demo_file.txt','update_name_demo_file.txt',(err)=>{
    if(err)throw err;
    console.log('file  Renamed');
})

Output

You can get the overall code on Github account.๐Ÿ˜‡

fileSystem๐Ÿคž

Thank you for reading my content. Be sure to follow and comment on what you want me to write about next ๐Ÿค“

Did you find this article valuable?

Support Saurabh verma by becoming a sponsor. Any amount is appreciated!

ย