fill.ts 3.6 KB
Newer Older
K
Kyle Carberry 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
import * as fs from "fs";
import * as util from "util";

const oldAccess = fs.access;
const existsWithinBinary = (path: fs.PathLike): Promise<boolean> => {
	return new Promise<boolean>((resolve) => {
		if (typeof path === "number") {
			if (path < 0) {
				return resolve(true);
			}
		}
		oldAccess(path, fs.constants.F_OK, (err) => {
			const exists = !err;
			const es = fs.existsSync(path);
			const res = !exists && es;
			resolve(res);
		});
	});
};

export const fillFs = () => {
	/**
	 * Refer to https://github.com/nexe/nexe/blob/master/src/fs/patch.ts
	 * For impls
	 */

	if (!process.env.CLI) {
		throw new Error("Should not fill FS when not in CLI");
	}

	interface FD {
		readonly path: string;
		position: number;
	}

	let lastFd = Number.MIN_SAFE_INTEGER;
	const fds = new Map<number, FD>();

	const replaceNative = <T extends keyof typeof fs>(propertyName: T, func: (callOld: () => void, ...args: any[]) => any, customPromisify?: (...args: any[]) => Promise<any>): void => {
		const oldFunc = (<any>fs)[propertyName];
		fs[propertyName] = (...args: any[]) => {
			try {
				return func(() => {
					return oldFunc(...args);
				}, ...args);
			} catch (ex) {
				return oldFunc(...args);
			}
		};
		if (customPromisify) {
			(<any>fs[propertyName])[util.promisify.custom] = customPromisify;
		}
	};

	replaceNative("access", (callNative, path, mode, callback) => {
		existsWithinBinary(path).then((exists) => {
			if (!exists) {
				return callNative();
			}

			return callback();
		});
	});

	replaceNative("exists", (callOld, path, callback) => {
		existsWithinBinary(path).then((exists) => {
			if (exists) {
				return callback(true);
			}

			return callOld();
		});
	}, (path) => new Promise((res) => fs.exists(path, res)));

	replaceNative("open", (callOld, path: fs.PathLike, flags: string | Number, mode: any, callback: any) => {
		existsWithinBinary(path).then((exists) => {
			if (!exists) {
				return callOld();
			}

			if (typeof mode === "function") {
				callback = mode;
				mode = undefined;
			}

			if (path === process.execPath) {
				return callOld();
			}

			const fd = lastFd++;
			fds.set(fd, {
				path: path.toString(),
				position: 0,
			});
			callback(undefined, fd);
		});
	});

	replaceNative("close", (callOld, fd: number, callback) => {
		if (!fds.has(fd)) {
			return callOld();
		}

		fds.delete(fd);
		callback();
	});

	replaceNative("read", (callOld, fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void, ) => {
		if (!fds.has(fd)) {
			return callOld();
		}

		const fileDesc = fds.get(fd)!;

		/**
		 * `readFile` is filled within nexe, but `read` is not
		 * https://github.com/nexe/nexe/blob/master/src/fs/patch.ts#L199
		 * We can simulate a real _read_ by reading the entire file.
		 * Efficiency can be improved here by storing the entire file in memory
		 * until it has been closed.
		 */
		return fs.readFile(fileDesc.path, (err, rb) => {
			if (err) {
				return callOld();
			}

			rb = rb.slice(position || fileDesc.position);
			const sliced = rb.slice(0, length);
			if (position === null) {
				fileDesc.position += sliced.byteLength;
			}
			buffer.set(sliced, offset);
			if (callback) {
				callback(undefined!, sliced.byteLength, buffer);
			}
		});
	}, (fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise<{
		bytesRead: number;
		buffer: Buffer;
	}> => {
			return new Promise((res, rej) => {
				fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
					if (err) {
						return rej(err);
					}

					res({
						bytesRead,
						buffer,
					});
				});
			});
		});
};