I understand that partial.lenses isn't necessarily the best solution to the following problem and that's besides the point in this question. I was trying to list files from a directory using L.collect from the partial.lenses library. Goal is just to get a flattened array of file names.
Problem: instead of using fs.readdirSync I would like to make use of asynchronous, Promise returning versions of the Node's fs API, in my optics.
The following would be the promisified version of the readdir:
const util = require('util')
const fs = require('fs')
const readdirAsync = util.promisify(fs.readdir)
Below is the actual implementation. I would like to know how I can replace the synchronous fs.readdirSync
in the readdir
function with an asynchronous version.
const L = require("partial.lenses")
const fs = require("fs")
const path = require("path")
const _ = require("lodash")
const basePath = path.basename(`${__dirname}/..`)
const isDirectory = dirent => {
return dirent instanceof fs.Dirent ? dirent.isDirectory() : false
}
const readDir = path => () => {
return fs.readdirSync(path, { withFileTypes: true })
}
const leafs = nodePath => {
return L.cond(
[
_.isArray,
L.lazy(() => [
L.elems,
L.choose(({ name }) => leafs(path.join(nodePath, name)))
])
],
[
isDirectory,
L.lazy(() => [
readDir(nodePath),
L.elems,
L.choose(({ name }) => leafs(path.join(nodePath, name)))
])
],
[L.identity]
)
}
const listFiles = async () =>
L.collect(
leafs(basePath),
fs.readdirSync(basePath, { withFileTypes: true })
)