Synchronous and Asynchronous File Delete in NodeJS
Synchronous Delete FileAsynchronous Delete Fileconst fs = require('fs');// Unlink is synchronous while unlinkSync is asynchronous.// Unlink returns error or nothing. If nothing then task is successful. If error, task is unsuccessful.fs.unlink('./test5.txt', err => {if (err) {console.log(err);} else {console.log("Done synchronously.");}});console.log("Independent line");
const fs = require('fs');try {fs.unlinkSync('./test5.txt');} catch (err) {console.log(err);} finally {console.log("Done operation!");}console.log("Independent line");
Synchronous and Asynchronous File Read in NodeJS
Synchronous Read FileAsynchronous Read Fileconst fs = require('fs');fs.readFile('./testfile.txt', "utf8", (err, data) => {if (err) {console.log.apply(err);} else {console.log(data);}});console.log("independent line");
const fs = require('fs');try {const content = fs.readFileSync('./testfile.txt', { encoding: "utf8" });} catch (err) {console.log(err);} finally {console.log("Done operation!");}console.log("Independent line");
Synchronous and Asynchronous File Write in NodeJS
Synchronous Write FileAsynchronous Read Fileconst fs = require('fs');fs.writeFile('./testfile.txt', "Content", err => {if (err) {console.log(err);} else {console.log("Successful writing!");}});console.log("independent line");
const fs = require('fs');try {fs.writeFileSync('./testfile.txt', "Async Content");} catch (err) {console.log(err);} finally {console.log("Done operation!")}console.log("independent line");
Synchronous and Asynchronous File Append in NodeJS
Synchronous Append FileAsynchronous Append Fileconst fs = require('fs');fs.appendFile('./testfile.txt', "Content", err => {if (err) {console.log(err);} else {console.log("Successful updating!");}});console.log("independent line");
That's it!const fs = require('fs');try {fs.appendFileSync('./testfile.txt', "Append Async Content");} catch (err) {console.log(err);} finally {console.log('Done Operation!')}console.log("independent line");
Comments
Post a Comment