SO question在获取目录和搜索文件方面提供了很多帮助。我正在尝试使我的readPackageFiles
函数符合使用给我的Parallel
函数;但是,我努力做到这一点。
错误:
UnhandledPromiseRejectionWarning: TypeError: Cannot use 'in' operator to search for 'throws' in 1
at readFile (/Users/harwood/udev/dotcom-components/tools/dependency-version-comparison/node_modules/jsonfile/index.js:22:16)
at Promise (/Users/harwood/udev/dotcom-components/tools/dependency-version-comparison/node_modules/universalify/index.js:13:12)
at new Promise (<anonymous>)
at readFile (/Users/harwood/udev/dotcom-components/tools/dependency-version-comparison/node_modules/universalify/index.js:7:14)
at Array.map (<anonymous>)
at /Users/harwood/udev/dotcom-components/tools/dependency-version-comparison/dist/index.js:1:1833
at <anonymous>
(node:70097) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 63)
(node:70097) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
/Users/harwood/udev/dotcom-components/tools/dependency-version-comparison/node_modules/jsonfile/index.js:43
callback(null, obj)
问题:如何使readPackageFiles
与Parallel兼容?
import {readdir, stat, readJson} from 'fs-extra';
import {join, basename} from 'path';
const Parallel = p =>
({
map: async f =>
Promise.all((await p).map(f))
,
filter: async f =>
Promise.all((await p).filter(f))
,
flatMap: async f =>
Promise.all((await p).map(f)).then(ys => [].concat(...ys))
,
});
const files = async (path = '.') =>
(await stat(path)).isDirectory()
? Parallel(readdir(path))
.flatMap(f => files(join(path, f)))
: [path];
const search = async (query, path = ".") =>
Parallel (files (path))
.filter (f => basename (f) === query);
// How can I write this to use Parallel
const readPackageFiles = async (packages) => await Promise.all(packages.map(async x => (await readJson(x))));
// this will not work but it's my attempt
const readPackageFilesNOTWORKING = async(path = ".") =>
Parallel (search('package.json', path))
.map (readJson)
用法:
search('package.json', '.')
.then(readPackageFiles)
.then(console.log);
答案 0 :(得分:1)
我希望您能进一步了解相关的问答环节。我怀疑您需要这样的东西,而此功能readPackages
位于我与您共享的first link中-
const { readFile } =
require ("fs") .promises
const readPackages = async (path = ".") =>
Parallel (search ("package.json", path))
.map (readFile)
.then
( buffers =>
buffers .map (b => JSON .parse (String (b)))
)
readPackages (".") .then (console.log, console.error)
// [ ... ]
请注意,我的任何答案都不需要fs-extra
。