DEV Community

Cover image for Working with the Node.js File System
Godswill Umukoro
Godswill Umukoro

Posted on • Edited on • Originally published at blog.godswillumukoro.com

Working with the Node.js File System

Firstly, we'll import the file system core module
const fs = require('fs');

Next, Let's read data from a file

fs.readFile('./notes.md', (err, data) => {
  if (err) {
    console.log(err);
  }
  console.log(data.toString());
});
Enter fullscreen mode Exit fullscreen mode

Great, we'll see how to write to files next, this code will create a new file if the referenced one does not exist

fs.writeFile('./note.md', 'I am a new file', () => {
    console.log('created a new file succesfully')
})
Enter fullscreen mode Exit fullscreen mode

Awesome, now let's delete the file if it already exists, or create it if it does not

if (fs.existsSync('./note.md')) {
  fs.unlink('./note.md', (err) => {
    if (err) {
      console.log(err);
    } else {
      console.log('file deleted');
    }
  });
} else {
  fs.writeFile('./note.md', 'I am a new file', () => {
    console.log('file created');
  });
}
Enter fullscreen mode Exit fullscreen mode

Next, let's work with directories. We'll see how to create a new directory or delete it if it already exists.

if (fs.existsSync('./new-folder')) {
  fs.rmdir('./new-folder', (err) => {
    if (err) {
      console.log(err);
    } else {
      console.log('folder deleted');
    }
  });
} else {
  fs.mkdir('./new-folder', (err) => {
    if (err) {
      console.log(err);
    } else {
      console.log('folder deleted');
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

Did you find this article helpful? Help spread the word so more people can learn how to work with the file system in Node.js. Follow me on Twitter and tell me how you found this useful.

Top comments (0)