Quantum
Quantum•11mo ago

Hoping for a clean way to get an array of filenames in directory

Trying to do something like this:
const files = Deno.readDirSync(Deno.cwd()).map(x => x.name);
const files = Deno.readDirSync(Deno.cwd()).map(x => x.name);
But I get this: Property 'map' does not exist on type 'Iterable<DirEntry>'. Is a for loop the only way?
6 Replies
Ayo Reis
Ayo Reis•11mo ago
You could turn the iterable into an array with Array.from and then map it, if memory is not a concern.
Fifth-Normal-Form
Fifth-Normal-Form•11mo ago
let files = [];
for await (const entry of Deno.readDirSync(Deno.cwd())) {
if (entry.isFile) files.push(entry.name);
}
let files = [];
for await (const entry of Deno.readDirSync(Deno.cwd())) {
if (entry.isFile) files.push(entry.name);
}
duncanmak
duncanmak•11mo ago
GitHub
GitHub - tc39/proposal-iterator-helpers: Methods for working with i...
Methods for working with iterators in ECMAScript. Contribute to tc39/proposal-iterator-helpers development by creating an account on GitHub.
npm
es-iterator-helpers
An ESnext spec-compliant iterator helpers shim/polyfill/replacement that works as far down as ES3.. Latest version: 1.0.15, last published: 4 months ago. Start using es-iterator-helpers in your project by running npm i es-iterator-helpers. There are 75 other projects in the npm registry using es-iterator-helpers.
javi
javi•11mo ago
You can use <Array>.fromAsync
const result = (await Array.fromAsync(Deno.readDir(Deno.cwd()))).filter(({ isFile }) => isFile);
const result = (await Array.fromAsync(Deno.readDir(Deno.cwd()))).filter(({ isFile }) => isFile);
Or go over the board with fp-ts, which is way more readable
import { task, function as func } from "npm:fp-ts"

const result = await func.pipe(
Deno.cwd(),
Deno.readDir,
Array.fromAsync,
task.of,
task.map((files) => files.filter(({ isFile }) => isFile)),
(fn) => fn()
)
import { task, function as func } from "npm:fp-ts"

const result = await func.pipe(
Deno.cwd(),
Deno.readDir,
Array.fromAsync,
task.of,
task.map((files) => files.filter(({ isFile }) => isFile)),
(fn) => fn()
)
Leokuma
Leokuma•11mo ago
import { walkSync } from "https://deno.land/std@0.213.0/fs/walk.ts"

const files = walkSync('.', {maxDepth: 1})
import { walkSync } from "https://deno.land/std@0.213.0/fs/walk.ts"

const files = walkSync('.', {maxDepth: 1})
https://deno.land/std@0.213.0/fs/mod.ts?s=WalkOptions
Quantum
QuantumOP•11mo ago
Thanks everyone! Also, walk is awesome. 🙂

Did you find this page helpful?