@ezdevlol/memfs
Version:
In-memory file-system with Node's fs API.
61 lines (60 loc) • 2.4 kB
JavaScript
import { NodeFileSystemHandle } from './NodeFileSystemHandle';
import { NodeFileSystemSyncAccessHandle } from './NodeFileSystemSyncAccessHandle';
import { assertCanWrite, basename, ctx as createCtx, newNotAllowedError } from './util';
import { NodeFileSystemWritableFileStream } from './NodeFileSystemWritableFileStream';
export class NodeFileSystemFileHandle extends NodeFileSystemHandle {
fs;
__path;
ctx;
constructor(fs, __path, ctx = {}) {
ctx = createCtx(ctx);
super('file', basename(__path, ctx.separator));
this.fs = fs;
this.__path = __path;
this.ctx = ctx;
}
/**
* Returns a {@link Promise} which resolves to a {@link File} object
* representing the state on disk of the entry represented by the handle.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle/getFile
*/
async getFile() {
try {
const path = this.__path;
const promises = this.fs.promises;
const stats = await promises.stat(path);
// TODO: Once implemented, use promises.readAsBlob() instead of promises.readFile().
const data = await promises.readFile(path);
const file = new File([data], this.name, { lastModified: stats.mtime.getTime() });
return file;
}
catch (error) {
if (error instanceof DOMException)
throw error;
if (error && typeof error === 'object') {
switch (error.code) {
case 'EPERM':
case 'EACCES':
throw newNotAllowedError();
}
}
throw error;
}
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle/createSyncAccessHandle
*/
get createSyncAccessHandle() {
if (!this.ctx.syncHandleAllowed)
return undefined;
return async () => new NodeFileSystemSyncAccessHandle(this.fs, this.__path, this.ctx);
}
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/FileSystemFileHandle/createWritable
*/
async createWritable({ keepExistingData = false } = { keepExistingData: false }) {
assertCanWrite(this.ctx.mode);
return new NodeFileSystemWritableFileStream(this.fs, this.__path, keepExistingData);
}
}