Quantum
Quantum•6mo 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•6mo ago
You could turn the iterable into an array with Array.from and then map it, if memory is not a concern.
NDH
NDH•6mo 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•6mo 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•6mo 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•6mo 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
Quantum•6mo ago
Thanks everyone! Also, walk is awesome. 🙂