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());
});
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')
})
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');
});
}
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');
}
});
}
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.