@neodx/vfs
Version:
Simple virtual file system - working dir context, lazy changes, different modes, integrations and moreover
60 lines (55 loc) • 2.25 kB
JavaScript
;
var fs = require('@neodx/fs');
var std = require('@neodx/std');
var createVfsPlugin = require('../_internal/create-vfs-plugin-1jK9qNm1.cjs');
const createFileApi = (vfs, path) => ({
path: vfs.resolve(path),
...std.mapKeysToObject(inheritedApis, key => vfs[key].bind(vfs, path))
});
const inheritedApis = ['tryRead', 'exists', 'delete', 'rename', 'write', 'read'];
function json() {
return createVfsPlugin.createVfsPlugin('json', vfs => {
vfs.jsonFile = path => createJsonFileApi(vfs, path);
vfs.readJson = (path, options) => readVfsJson(vfs, path, options);
vfs.writeJson = (path, json, options) => writeVfsJson(vfs, path, json, options);
vfs.updateJson = (path, updater, options) => updateVfsJson(vfs, path, updater, options);
return vfs;
});
}
function createJsonFileApi(vfs, path) {
return {
...createFileApi(vfs, path),
read: options => readVfsJson(vfs, path, options),
tryRead: options => readVfsJson(vfs, path, options).catch(() => null),
write: (json, options) => writeVfsJson(vfs, path, json, options),
update: (updater, options) => updateVfsJson(vfs, path, updater, options),
experimental_toResource: async (defaultValue, options) => {
const data = (await readVfsJson(vfs, path, options)) ?? defaultValue;
return {
data,
[Symbol.asyncDispose]: async () => await writeVfsJson(vfs, path, data, options)
};
}
};
}
async function readVfsJson(vfs, path, options) {
try {
return fs.parseJson(await vfs.read(path, 'utf-8'), options);
} catch (error) {
throw new Error(`Cannot parse ${path}:\n${error.message}`);
}
}
async function writeVfsJson(vfs, path, json, options) {
return await vfs.write(path, fs.serializeJson(json, options));
}
async function updateVfsJson(vfs, path, updater, options) {
// TODO Implement support for empty, damaged, or nonexistent files
const current = await readVfsJson(vfs, path, options);
return await writeVfsJson(vfs, path, (await updater(current)) ?? current, options);
}
exports.createJsonFileApi = createJsonFileApi;
exports.json = json;
exports.readVfsJson = readVfsJson;
exports.updateVfsJson = updateVfsJson;
exports.writeVfsJson = writeVfsJson;
//# sourceMappingURL=json.cjs.map