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`);
    }
});

About Author

Mathias Bothe Contact me

I am Mathias, born 38 years ago in Heidelberg, Germany. Today I am living in Munich and Stockholm. I am a passionate IT freelancer with more than 14 years experience in programming, especially in developing web based applications for companies that range from small startups to the big players out there. I am founder of bosy.com, creator of the security service platform BosyProtect© and initiator of several other software projects.