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