NodeJS: File system operations
Check if a file exists
Here are a couple of sync and async ways to check if a file exists via NodeJS.
const fs = require('fs'); const path = require('path'); const dirname = path.join('E:', 'myFolder''); /* Sync #1 */ console.log(fs.existsSync(dirname)); /* Sync #2 */ try { const stat = fs.statSync(dirname) } catch (exc) { console.error(exc); } /* Async #1 */ fs.access(dirname, (err, res) => { if(err) { console.error(err); } }); /* Async #2 */ fs.stat(dirname, (err, res) => { if(err) { console.log(err); } });
Reading files within a directory
const fs = require('fs'); const path = require('path'); const dirname = path.join('E:', 'myFolder'); const files = fs.readdirSync(dirname) files.forEach((file) => { console.log(file); })
Watching files
const fs = require('fs'); const path = require('path'); const dirname = path.join('E:', 'myFolder'); fs.watch(dirname, (evt, filename) => { if(evt === 'rename') { console.log(`${filename} was renamed`); } });