#How to read write files synchronously with fs
1 2 3 4 5 6 7 8 9 10 11 |
const fs = require('fs') const str = '1Hello world!' // save data fs.writeFileSync(`${__dirname}/data.html`, str) // read data const d = fs.readFileSync(`${__dirname}/data.html`, 'utf8') console.log('d = ', d) // d = 1Hello world! |
#How to read write files asynchronously with fs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const fs = require('fs') const str = 'Hello world!' // save data fs.writeFile(`${__dirname}/data.html`, str, err => { if (err) throw err console.log('saved'); }) // read data fs.readFile(`${__dirname}/data.html`, 'utf8', (err, data) => { if (err) throw err console.log('data = ', data); // data = Hello world! }) |
#How to check existence of files
Sometimes we have to know whether a file exists or not. To do this we’ll be using a node.js fs module. We could check synchronously by using and asynchronously with
Here is an example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const fs = require('fs') // asynchronous fs.stat(`${__dirname}/model`, (err, stats) => { if(stats.isFile()){ console.log('file'); } else if (stats.isDirectory()) { console.log('directory'); } else { console.log('others'); } }) // synchronous if (fs.lstatSync(`${__dirname}/package.json`).isFile()){ console.log('file'); } if (fs.statSync(`${__dirname}/node_modules`).isDirectory()){ console.log('directory'); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// check file or directory existance in async an sync way const fs = require('fs') // sync if (fs.statSync(`${__dirname}/package.json`).isFile()) { console.log('sync: file'); } if (fs.statSync(`${__dirname}/.`).isDirectory()) { console.log('sync: directory'); } // async fs.stat(`${__dirname}/package.json`, (err, stats) => { if (err) throw err if (stats.isFile()) { console.log('async: file'); } }) fs.stat(`${__dirname}/.`, (err, stat) => { if (err) throw err if (stat.isDirectory) { console.log('async: directory'); } }) |
We can check different thing with next functions
1 2 3 4 5 6 7 |
stats.isFile() stats.isDirectory() stats.isBlockDevice() stats.isCharacterDevice() stats.isSymbolicLink() (only valid with fs.lstat()) stats.isFIFO() stats.isSocket() |
Here is a link on the documentation link
the end