63 lines
2.1 KiB
JavaScript
63 lines
2.1 KiB
JavaScript
import { readdirSync, readdir } from 'fs';
|
|
import { validateArgument } from './utils/validate.js';
|
|
import { isMacintosh } from './utils/platform.js';
|
|
import { normalizeNFC } from './utils/strings.js';
|
|
export function validateInput(methodName, path) {
|
|
const methodSignature = methodName + '(path)';
|
|
validateArgument(methodSignature, 'path', path, ['string', 'undefined']);
|
|
}
|
|
export function _readdirSync(path) {
|
|
// Mac: uses NFD unicode form on disk, but we want NFC
|
|
// See also https://github.com/nodejs/node/issues/2165
|
|
if (isMacintosh) {
|
|
return readdirSync(path).map(c => normalizeNFC(c));
|
|
}
|
|
return readdirSync(path);
|
|
}
|
|
// ---------------------------------------------------------
|
|
// Sync
|
|
// ---------------------------------------------------------
|
|
export function sync(path) {
|
|
try {
|
|
return _readdirSync(path);
|
|
}
|
|
catch (err) {
|
|
if (err.code === 'ENOENT') {
|
|
// Doesn't exist. Return undefined instead of throwing.
|
|
return undefined;
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
// ---------------------------------------------------------
|
|
// Async
|
|
// ---------------------------------------------------------
|
|
function readdirASync(path) {
|
|
// export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void;
|
|
// Mac: uses NFD unicode form on disk, but we want NFC
|
|
// See also https://github.com/nodejs/node/issues/2165
|
|
return new Promise((resolve, reject) => {
|
|
if (isMacintosh) {
|
|
readdir(path, (err, files) => {
|
|
if (err) {
|
|
reject(err);
|
|
}
|
|
resolve(files);
|
|
});
|
|
}
|
|
readdir(path, (err, files) => {
|
|
if (err) {
|
|
reject(err);
|
|
}
|
|
resolve(files);
|
|
});
|
|
});
|
|
}
|
|
export function async(path) {
|
|
return new Promise((resolve, reject) => {
|
|
readdirASync(path)
|
|
.then((list) => resolve(list))
|
|
.catch(err => (err.code === 'ENOENT' ? resolve(undefined) : reject(err)));
|
|
});
|
|
}
|