Check to see if a file is a directory in NodeJS

  • Language:: Javascript

  • Type:: Back-end

  • Context:: Check to see if the file is a directory

  • Description

  • Snippet

const fs = require('fs').promises;
 
(async() => {
    const stat = await fs.lstat('test.txt');
    console.log(stat.isFile());
})().catch(console.error);
const fs = require("fs");
 
let path = "/path/to/something";
 
fs.lstat(path, (err, stats) => {
 
    if(err)
        return console.log(err); //Handle error
 
    console.log(`Is file: ${stats.isFile()}`);
    console.log(`Is directory: ${stats.isDirectory()}`);
    console.log(`Is symbolic link: ${stats.isSymbolicLink()}`);
    console.log(`Is FIFO: ${stats.isFIFO()}`);
    console.log(`Is socket: ${stats.isSocket()}`);
    console.log(`Is character device: ${stats.isCharacterDevice()}`);
    console.log(`Is block device: ${stats.isBlockDevice()}`);
});

📇Additional Metadata