Getting Started With Node – Course

How to Create delete and rename files

The file system module provides three methods to create files:

  1. fs.open()
  2. fs.writeFile()
  3. fs.appendFile()

fs.open() method opens new file or create new empty file if does not exist in the specified path.

It takes the second parameter which acts as a flag such as w for writing, w+ for reading and writing etc.

Code:

const fs = require('fs');

fs.open('file.txt', 'w', (err, file) => {
  if (err) throw err;
  console.log('Saved!');
});

fs.writeFile() method allows to create or replace file with the content. If a file exists, it will replace the content with the provided content and if the file does not exist, it will create it.

const fs = require('fs');

fs.writeFile('file.txt', 'Hello Word!', (err) => {
  if (err) throw err;
  console.log('Saved!');
});

fs.appendFile() method appends the provided content at the end of the file.

const fs = require('fs');

fs.appendFile('file.txt', ' Hello World', (err) => {
  if (err) throw err;
  console.log('Updated!');
})

To delete a file, we can use fs.unlink() method.

const fs = require('fs');

fs.unlink('file.txt', (err) => {
  if (err) throw err;
  console.log('File deleted!');
});

To rename a file, we can use fs.rename() method.

const fs = require('fs');

fs.rename('newfile.txt', 'oldfile.txt', (err) => {
  if (err) throw err;
  console.log('File Renamed!');
});

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.