HOW TO WRITE FILES IN NODEJS

NODE

(quick guide & examples)

WRITE FILE fs.writeFile("MY.TXT", "TXT", err => {   if (err) { console.log(err); }   else { console.log("OK"); } });

WRITE FILE (ASYNC)

01

APPEND FILE fs.appendFile("MY.TXT", "TET", err => {   if (err) { console.log(err); }   else { console.log("OK"); } });

FILE SYSTEM MODULE const fs = require("fs");

WRITE FILE try { fs.writeFileSync("MY.TXT", "TXT"); } catch (err) { console.log(err); }

WRITE FILE (SYNC)

02

APPEND FILE try { fs.appendFileSync("MY.TXT", "TXT"); }  catch (err) { console.log(err); }

FILE SYSTEM MODULE const fs = require("fs");

OPEN & WRITE FILE fs.open("MY.txt", "a", (err, fh) => {   if (err) { console.log(err); }   else {     fs.write(fh, "TXT", (err, bytes) => {       if (err) { console.log(err); }       else { console.log("OK"); }     });   } });

WRITE FILE (LOW LEVEL)

03

FILE SYSTEM MODULE const fs = require("fs");

CREATE FILE STREAM const fs = require("fs"), stream = fs.createWriteStream("MYTXT");

WRITE FILE (STREAM)

04

WRITE TO STREAM stream.write("TXT"); stream.end();