DEV Community 👩‍💻👨‍💻

Neha Sharma
Neha Sharma

Posted on

#3 FS Module (Promise API)

In the last blog you read about fs module (callback API). In today's blog we will go through the Promise API.

Everything will remain the same as what we learned in our last blog. The only change is using promise API will return the promise rather than callback.

You can check the code here

  1. Write
// write file
(async function(){
    try {
      const filehandle = await fsPromises.writeFile('userlogs.txt', 'system logs...','utf8');
      console.log('file created')
    } 
    catch(err){
      console.log(err)
    }
  }());
Enter fullscreen mode Exit fullscreen mode

2 . Append

// append file
(async function(){
    try {
      const filehandle = await fsPromises.appendFile('logs.txt', 'New logs', 'utf8');
      console.log(filehandle)
    } 
    catch(err){
      console.log(err)
    }
  }());

Enter fullscreen mode Exit fullscreen mode

3 . Read

// read file
(async function(){
    try {
      const filehandle = await fsPromises.readFile('logs.txt', 'utf8');
      console.log(filehandle)
    } 
    catch(err){
      console.log(err)
    }
  }());
Enter fullscreen mode Exit fullscreen mode

4 . Rename

// rename file
(async function(){
    try {
      const filehandle = await fsPromises.rename('logs.txt', 'userlogs.txt');
      console.log('File name updated')
    } 
    catch(err){
      console.log(err)
    }
}());
Enter fullscreen mode Exit fullscreen mode

5 . Delete

// delete file
(async function(){
    try {
      const filehandle = await fsPromises.unlink('userlogs.txt');
      console.log('File deleted')
    } 
    catch(err){
      console.log(err)
    }
}());
Enter fullscreen mode Exit fullscreen mode

Resources

NodeJS Documentation

Like it? Do follow me on Twitter and Linkedin.

Top comments (0)

Classic DEV Post:

Visualizing Promises and Async/Await 🤯

async await