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?
Required functionality is added in: v10.10.0, you have to update node.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With