Working with the Node.js File System
Godswill Umukoro
Posted on June 13, 2022
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.
💖 💪 🙅 🚩
Godswill Umukoro
Posted on June 13, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
reactnative I have an error when installing and using the react-native-bluetooth-serial-next library on an ios device.
November 29, 2024
programming Supercharge Your Node.js: WebAssembly's Game-Changing Performance Boost
November 28, 2024