Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get array of fs.Dirent from fs.readdir

Tags:

node.js

fs

I am using node 8.10.0.

fs.readdir() returns an array of filenames and child directory names, or fs.Dirents[].

I can't get that to work. Here's a simple example:

console.log(require("fs").readdirSync("/", {withFileTypes:true}));

This gives me an array of strings (e.g. ["bin", "mnt", "usr", "var", ...]), not an array of fs.Dirent objects (which is what I want).

How do I get this to work?

like image 231
lonix Avatar asked Sep 07 '18 09:09

lonix


2 Answers

Required functionality is added in: v10.10.0, you have to update node.

like image 75
mehta-rohan Avatar answered Oct 19 '22 23:10

mehta-rohan


I've hit the same problem and although I have the latest node.js (v10.16 currently) and intellisense in VS Code is consistent with the online documentation, the run-time reality surprised me. But that is because the code gets executed by node.js v10.2 (inside a VS Code extension).

So on node.js 10.2, this code works for me to get files in a directory:

import * as fs from 'fs';
import util = require('util');
export const readdir = util.promisify(fs.readdir);

let fileNames: string[] = await readdir(directory)
    // keep only files, not directories
    .filter(fileName => fs.statSync(path.join(directory, fileName)).isFile());

On the latest node.js, the same code could be simplified this way:

let fileEnts: fs.Dirent[] = await fs.promises.readdir(directory, { withFileTypes: true });

let fileNames: string[] = fileEnts
    .filter(fileEnt => fileEnt.isFile())
    .map(fileEnt => fileEnt.name);

The code snippets are in Typescript.

like image 3
Jan Dolejsi Avatar answered Oct 19 '22 21:10

Jan Dolejsi