DEV Community

Neha Sharma
Neha Sharma

Posted on

3 1

#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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free