Node Foundamentals — Part 2, filesystem

Reading files

const fs = require('fs');
fs.readdir('./', (err, content) => {
if(err) return err;
console.log(content);
});
fs.readFile('filename.html', 'UTF-8', (err, content) => {  
console.log(content);
});

Writing files

const fs = require('fs');
fs.writeFile('./filename.html', 
`File content here`, 'utf8', (err) => {
if(err) return err;
console.log("Success");
});
fs.appendFile('./filename.html', `... and here`, 'utf8', (err)=> {
if(err) return err;
console.log("Success");
});

Create a directory

const fs = require('fs');
if(!fs.exists("my_dir")) {
fs.mkdir("my_dir", (err) => {
if(err) return err;
fs.writeFile("./my_dir/new.html",
'new file in new dir', (err) => {
if(err) return err;
console.log('Directory and file saved')
});
});
}

Delete a file or a directoty

const fs = require('fs');
// Delete a directory
fs.rmdir('./my_dir', (err) => {
if(err) return err;
});
// Delete a file
fs.unlink('./my_dir/file.html', (err) => {
if(err) return err;
});

Rename or move files or directories

const fs = require('fs');
// Rename files
fs.rename('./newfile.js', 'other_dir/hello.js', (err) => {
if(err) return err;
});
// Rename or move Directories
fs.rename('./new_dir/child', './other_parent', (err) => {
if(err) return err;
});