volume.js 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.FSWatcher = exports.StatWatcher = exports.Volume = exports.toUnixTimestamp = exports.bufferToEncoding = exports.dataToBuffer = exports.dataToStr = exports.pathToSteps = exports.filenameToSteps = exports.pathToFilename = exports.flagsToNumber = exports.FLAGS = void 0;
  4. const pathModule = require("path");
  5. const node_1 = require("./node");
  6. const Stats_1 = require("./Stats");
  7. const Dirent_1 = require("./Dirent");
  8. const buffer_1 = require("./internal/buffer");
  9. const setImmediate_1 = require("./setImmediate");
  10. const process_1 = require("./process");
  11. const setTimeoutUnref_1 = require("./setTimeoutUnref");
  12. const stream_1 = require("stream");
  13. const constants_1 = require("./constants");
  14. const events_1 = require("events");
  15. const encoding_1 = require("./encoding");
  16. const errors = require("./internal/errors");
  17. const util = require("util");
  18. const promises_1 = require("./node/promises");
  19. const resolveCrossPlatform = pathModule.resolve;
  20. const { O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_EXCL, O_TRUNC, O_APPEND, O_SYNC, O_DIRECTORY, F_OK, COPYFILE_EXCL, COPYFILE_FICLONE_FORCE, } = constants_1.constants;
  21. const { sep, relative, join, dirname } = pathModule.posix ? pathModule.posix : pathModule;
  22. const isWin = process_1.default.platform === 'win32';
  23. const kMinPoolSpace = 128;
  24. // const kMaxLength = require('buffer').kMaxLength;
  25. // ---------------------------------------- Error messages
  26. // TODO: Use `internal/errors.js` in the future.
  27. const ERRSTR = {
  28. PATH_STR: 'path must be a string or Buffer',
  29. // FD: 'file descriptor must be a unsigned 32-bit integer',
  30. FD: 'fd must be a file descriptor',
  31. MODE_INT: 'mode must be an int',
  32. CB: 'callback must be a function',
  33. UID: 'uid must be an unsigned int',
  34. GID: 'gid must be an unsigned int',
  35. LEN: 'len must be an integer',
  36. ATIME: 'atime must be an integer',
  37. MTIME: 'mtime must be an integer',
  38. PREFIX: 'filename prefix is required',
  39. BUFFER: 'buffer must be an instance of Buffer or StaticBuffer',
  40. OFFSET: 'offset must be an integer',
  41. LENGTH: 'length must be an integer',
  42. POSITION: 'position must be an integer',
  43. };
  44. const ERRSTR_OPTS = tipeof => `Expected options to be either an object or a string, but got ${tipeof} instead`;
  45. // const ERRSTR_FLAG = flag => `Unknown file open flag: ${flag}`;
  46. const ENOENT = 'ENOENT';
  47. const EBADF = 'EBADF';
  48. const EINVAL = 'EINVAL';
  49. const EPERM = 'EPERM';
  50. const EPROTO = 'EPROTO';
  51. const EEXIST = 'EEXIST';
  52. const ENOTDIR = 'ENOTDIR';
  53. const EMFILE = 'EMFILE';
  54. const EACCES = 'EACCES';
  55. const EISDIR = 'EISDIR';
  56. const ENOTEMPTY = 'ENOTEMPTY';
  57. const ENOSYS = 'ENOSYS';
  58. const ERR_FS_EISDIR = 'ERR_FS_EISDIR';
  59. function formatError(errorCode, func = '', path = '', path2 = '') {
  60. let pathFormatted = '';
  61. if (path)
  62. pathFormatted = ` '${path}'`;
  63. if (path2)
  64. pathFormatted += ` -> '${path2}'`;
  65. switch (errorCode) {
  66. case ENOENT:
  67. return `ENOENT: no such file or directory, ${func}${pathFormatted}`;
  68. case EBADF:
  69. return `EBADF: bad file descriptor, ${func}${pathFormatted}`;
  70. case EINVAL:
  71. return `EINVAL: invalid argument, ${func}${pathFormatted}`;
  72. case EPERM:
  73. return `EPERM: operation not permitted, ${func}${pathFormatted}`;
  74. case EPROTO:
  75. return `EPROTO: protocol error, ${func}${pathFormatted}`;
  76. case EEXIST:
  77. return `EEXIST: file already exists, ${func}${pathFormatted}`;
  78. case ENOTDIR:
  79. return `ENOTDIR: not a directory, ${func}${pathFormatted}`;
  80. case EISDIR:
  81. return `EISDIR: illegal operation on a directory, ${func}${pathFormatted}`;
  82. case EACCES:
  83. return `EACCES: permission denied, ${func}${pathFormatted}`;
  84. case ENOTEMPTY:
  85. return `ENOTEMPTY: directory not empty, ${func}${pathFormatted}`;
  86. case EMFILE:
  87. return `EMFILE: too many open files, ${func}${pathFormatted}`;
  88. case ENOSYS:
  89. return `ENOSYS: function not implemented, ${func}${pathFormatted}`;
  90. case ERR_FS_EISDIR:
  91. return `[ERR_FS_EISDIR]: Path is a directory: ${func} returned EISDIR (is a directory) ${path}`;
  92. default:
  93. return `${errorCode}: error occurred, ${func}${pathFormatted}`;
  94. }
  95. }
  96. function createError(errorCode, func = '', path = '', path2 = '', Constructor = Error) {
  97. const error = new Constructor(formatError(errorCode, func, path, path2));
  98. error.code = errorCode;
  99. if (path) {
  100. error.path = path;
  101. }
  102. return error;
  103. }
  104. // ---------------------------------------- Flags
  105. // List of file `flags` as defined by Node.
  106. var FLAGS;
  107. (function (FLAGS) {
  108. // Open file for reading. An exception occurs if the file does not exist.
  109. FLAGS[FLAGS["r"] = O_RDONLY] = "r";
  110. // Open file for reading and writing. An exception occurs if the file does not exist.
  111. FLAGS[FLAGS["r+"] = O_RDWR] = "r+";
  112. // Open file for reading in synchronous mode. Instructs the operating system to bypass the local file system cache.
  113. FLAGS[FLAGS["rs"] = O_RDONLY | O_SYNC] = "rs";
  114. FLAGS[FLAGS["sr"] = FLAGS.rs] = "sr";
  115. // Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about using this with caution.
  116. FLAGS[FLAGS["rs+"] = O_RDWR | O_SYNC] = "rs+";
  117. FLAGS[FLAGS["sr+"] = FLAGS['rs+']] = "sr+";
  118. // Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
  119. FLAGS[FLAGS["w"] = O_WRONLY | O_CREAT | O_TRUNC] = "w";
  120. // Like 'w' but fails if path exists.
  121. FLAGS[FLAGS["wx"] = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL] = "wx";
  122. FLAGS[FLAGS["xw"] = FLAGS.wx] = "xw";
  123. // Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
  124. FLAGS[FLAGS["w+"] = O_RDWR | O_CREAT | O_TRUNC] = "w+";
  125. // Like 'w+' but fails if path exists.
  126. FLAGS[FLAGS["wx+"] = O_RDWR | O_CREAT | O_TRUNC | O_EXCL] = "wx+";
  127. FLAGS[FLAGS["xw+"] = FLAGS['wx+']] = "xw+";
  128. // Open file for appending. The file is created if it does not exist.
  129. FLAGS[FLAGS["a"] = O_WRONLY | O_APPEND | O_CREAT] = "a";
  130. // Like 'a' but fails if path exists.
  131. FLAGS[FLAGS["ax"] = O_WRONLY | O_APPEND | O_CREAT | O_EXCL] = "ax";
  132. FLAGS[FLAGS["xa"] = FLAGS.ax] = "xa";
  133. // Open file for reading and appending. The file is created if it does not exist.
  134. FLAGS[FLAGS["a+"] = O_RDWR | O_APPEND | O_CREAT] = "a+";
  135. // Like 'a+' but fails if path exists.
  136. FLAGS[FLAGS["ax+"] = O_RDWR | O_APPEND | O_CREAT | O_EXCL] = "ax+";
  137. FLAGS[FLAGS["xa+"] = FLAGS['ax+']] = "xa+";
  138. })(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
  139. function flagsToNumber(flags) {
  140. if (typeof flags === 'number')
  141. return flags;
  142. if (typeof flags === 'string') {
  143. const flagsNum = FLAGS[flags];
  144. if (typeof flagsNum !== 'undefined')
  145. return flagsNum;
  146. }
  147. // throw new TypeError(formatError(ERRSTR_FLAG(flags)));
  148. throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'flags', flags);
  149. }
  150. exports.flagsToNumber = flagsToNumber;
  151. // ---------------------------------------- Options
  152. function getOptions(defaults, options) {
  153. let opts;
  154. if (!options)
  155. return defaults;
  156. else {
  157. const tipeof = typeof options;
  158. switch (tipeof) {
  159. case 'string':
  160. opts = Object.assign({}, defaults, { encoding: options });
  161. break;
  162. case 'object':
  163. opts = Object.assign({}, defaults, options);
  164. break;
  165. default:
  166. throw TypeError(ERRSTR_OPTS(tipeof));
  167. }
  168. }
  169. if (opts.encoding !== 'buffer')
  170. (0, encoding_1.assertEncoding)(opts.encoding);
  171. return opts;
  172. }
  173. function optsGenerator(defaults) {
  174. return options => getOptions(defaults, options);
  175. }
  176. function validateCallback(callback) {
  177. if (typeof callback !== 'function')
  178. throw TypeError(ERRSTR.CB);
  179. return callback;
  180. }
  181. function optsAndCbGenerator(getOpts) {
  182. return (options, callback) => typeof options === 'function' ? [getOpts(), options] : [getOpts(options), validateCallback(callback)];
  183. }
  184. const optsDefaults = {
  185. encoding: 'utf8',
  186. };
  187. const getDefaultOpts = optsGenerator(optsDefaults);
  188. const getDefaultOptsAndCb = optsAndCbGenerator(getDefaultOpts);
  189. const readFileOptsDefaults = {
  190. flag: 'r',
  191. };
  192. const getReadFileOptions = optsGenerator(readFileOptsDefaults);
  193. const writeFileDefaults = {
  194. encoding: 'utf8',
  195. mode: 438 /* MODE.DEFAULT */,
  196. flag: FLAGS[FLAGS.w],
  197. };
  198. const getWriteFileOptions = optsGenerator(writeFileDefaults);
  199. const appendFileDefaults = {
  200. encoding: 'utf8',
  201. mode: 438 /* MODE.DEFAULT */,
  202. flag: FLAGS[FLAGS.a],
  203. };
  204. const getAppendFileOpts = optsGenerator(appendFileDefaults);
  205. const getAppendFileOptsAndCb = optsAndCbGenerator(getAppendFileOpts);
  206. const realpathDefaults = optsDefaults;
  207. const getRealpathOptions = optsGenerator(realpathDefaults);
  208. const getRealpathOptsAndCb = optsAndCbGenerator(getRealpathOptions);
  209. const mkdirDefaults = {
  210. mode: 511 /* MODE.DIR */,
  211. recursive: false,
  212. };
  213. const getMkdirOptions = (options) => {
  214. if (typeof options === 'number')
  215. return Object.assign({}, mkdirDefaults, { mode: options });
  216. return Object.assign({}, mkdirDefaults, options);
  217. };
  218. const rmdirDefaults = {
  219. recursive: false,
  220. };
  221. const getRmdirOptions = (options) => {
  222. return Object.assign({}, rmdirDefaults, options);
  223. };
  224. const getRmOpts = optsGenerator(optsDefaults);
  225. const getRmOptsAndCb = optsAndCbGenerator(getRmOpts);
  226. const readdirDefaults = {
  227. encoding: 'utf8',
  228. withFileTypes: false,
  229. };
  230. const getReaddirOptions = optsGenerator(readdirDefaults);
  231. const getReaddirOptsAndCb = optsAndCbGenerator(getReaddirOptions);
  232. const statDefaults = {
  233. bigint: false,
  234. };
  235. const getStatOptions = (options = {}) => Object.assign({}, statDefaults, options);
  236. const getStatOptsAndCb = (options, callback) => typeof options === 'function' ? [getStatOptions(), options] : [getStatOptions(options), validateCallback(callback)];
  237. // ---------------------------------------- Utility functions
  238. function getPathFromURLPosix(url) {
  239. if (url.hostname !== '') {
  240. throw new errors.TypeError('ERR_INVALID_FILE_URL_HOST', process_1.default.platform);
  241. }
  242. const pathname = url.pathname;
  243. for (let n = 0; n < pathname.length; n++) {
  244. if (pathname[n] === '%') {
  245. const third = pathname.codePointAt(n + 2) | 0x20;
  246. if (pathname[n + 1] === '2' && third === 102) {
  247. throw new errors.TypeError('ERR_INVALID_FILE_URL_PATH', 'must not include encoded / characters');
  248. }
  249. }
  250. }
  251. return decodeURIComponent(pathname);
  252. }
  253. function pathToFilename(path) {
  254. if (typeof path !== 'string' && !buffer_1.Buffer.isBuffer(path)) {
  255. try {
  256. if (!(path instanceof require('url').URL))
  257. throw new TypeError(ERRSTR.PATH_STR);
  258. }
  259. catch (err) {
  260. throw new TypeError(ERRSTR.PATH_STR);
  261. }
  262. path = getPathFromURLPosix(path);
  263. }
  264. const pathString = String(path);
  265. nullCheck(pathString);
  266. // return slash(pathString);
  267. return pathString;
  268. }
  269. exports.pathToFilename = pathToFilename;
  270. let resolve = (filename, base = process_1.default.cwd()) => resolveCrossPlatform(base, filename);
  271. if (isWin) {
  272. const _resolve = resolve;
  273. const { unixify } = require('fs-monkey/lib/correctPath');
  274. resolve = (filename, base) => unixify(_resolve(filename, base));
  275. }
  276. function filenameToSteps(filename, base) {
  277. const fullPath = resolve(filename, base);
  278. const fullPathSansSlash = fullPath.substring(1);
  279. if (!fullPathSansSlash)
  280. return [];
  281. return fullPathSansSlash.split(sep);
  282. }
  283. exports.filenameToSteps = filenameToSteps;
  284. function pathToSteps(path) {
  285. return filenameToSteps(pathToFilename(path));
  286. }
  287. exports.pathToSteps = pathToSteps;
  288. function dataToStr(data, encoding = encoding_1.ENCODING_UTF8) {
  289. if (buffer_1.Buffer.isBuffer(data))
  290. return data.toString(encoding);
  291. else if (data instanceof Uint8Array)
  292. return (0, buffer_1.bufferFrom)(data).toString(encoding);
  293. else
  294. return String(data);
  295. }
  296. exports.dataToStr = dataToStr;
  297. function dataToBuffer(data, encoding = encoding_1.ENCODING_UTF8) {
  298. if (buffer_1.Buffer.isBuffer(data))
  299. return data;
  300. else if (data instanceof Uint8Array)
  301. return (0, buffer_1.bufferFrom)(data);
  302. else
  303. return (0, buffer_1.bufferFrom)(String(data), encoding);
  304. }
  305. exports.dataToBuffer = dataToBuffer;
  306. function bufferToEncoding(buffer, encoding) {
  307. if (!encoding || encoding === 'buffer')
  308. return buffer;
  309. else
  310. return buffer.toString(encoding);
  311. }
  312. exports.bufferToEncoding = bufferToEncoding;
  313. function nullCheck(path, callback) {
  314. if (('' + path).indexOf('\u0000') !== -1) {
  315. const er = new Error('Path must be a string without null bytes');
  316. er.code = ENOENT;
  317. if (typeof callback !== 'function')
  318. throw er;
  319. process_1.default.nextTick(callback, er);
  320. return false;
  321. }
  322. return true;
  323. }
  324. function _modeToNumber(mode, def) {
  325. if (typeof mode === 'number')
  326. return mode;
  327. if (typeof mode === 'string')
  328. return parseInt(mode, 8);
  329. if (def)
  330. return modeToNumber(def);
  331. return undefined;
  332. }
  333. function modeToNumber(mode, def) {
  334. const result = _modeToNumber(mode, def);
  335. if (typeof result !== 'number' || isNaN(result))
  336. throw new TypeError(ERRSTR.MODE_INT);
  337. return result;
  338. }
  339. function isFd(path) {
  340. return path >>> 0 === path;
  341. }
  342. function validateFd(fd) {
  343. if (!isFd(fd))
  344. throw TypeError(ERRSTR.FD);
  345. }
  346. // converts Date or number to a fractional UNIX timestamp
  347. function toUnixTimestamp(time) {
  348. // tslint:disable-next-line triple-equals
  349. if (typeof time === 'string' && +time == time) {
  350. return +time;
  351. }
  352. if (time instanceof Date) {
  353. return time.getTime() / 1000;
  354. }
  355. if (isFinite(time)) {
  356. if (time < 0) {
  357. return Date.now() / 1000;
  358. }
  359. return time;
  360. }
  361. throw new Error('Cannot parse time: ' + time);
  362. }
  363. exports.toUnixTimestamp = toUnixTimestamp;
  364. function validateUid(uid) {
  365. if (typeof uid !== 'number')
  366. throw TypeError(ERRSTR.UID);
  367. }
  368. function validateGid(gid) {
  369. if (typeof gid !== 'number')
  370. throw TypeError(ERRSTR.GID);
  371. }
  372. function flattenJSON(nestedJSON) {
  373. const flatJSON = {};
  374. function flatten(pathPrefix, node) {
  375. for (const path in node) {
  376. const contentOrNode = node[path];
  377. const joinedPath = join(pathPrefix, path);
  378. if (typeof contentOrNode === 'string') {
  379. flatJSON[joinedPath] = contentOrNode;
  380. }
  381. else if (typeof contentOrNode === 'object' && contentOrNode !== null && Object.keys(contentOrNode).length > 0) {
  382. // empty directories need an explicit entry and therefore get handled in `else`, non-empty ones are implicitly considered
  383. flatten(joinedPath, contentOrNode);
  384. }
  385. else {
  386. // without this branch null, empty-object or non-object entries would not be handled in the same way
  387. // by both fromJSON() and fromNestedJSON()
  388. flatJSON[joinedPath] = null;
  389. }
  390. }
  391. }
  392. flatten('', nestedJSON);
  393. return flatJSON;
  394. }
  395. /**
  396. * `Volume` represents a file system.
  397. */
  398. class Volume {
  399. static fromJSON(json, cwd) {
  400. const vol = new Volume();
  401. vol.fromJSON(json, cwd);
  402. return vol;
  403. }
  404. static fromNestedJSON(json, cwd) {
  405. const vol = new Volume();
  406. vol.fromNestedJSON(json, cwd);
  407. return vol;
  408. }
  409. get promises() {
  410. if (this.promisesApi === null)
  411. throw new Error('Promise is not supported in this environment.');
  412. return this.promisesApi;
  413. }
  414. constructor(props = {}) {
  415. // I-node number counter.
  416. this.ino = 0;
  417. // A mapping for i-node numbers to i-nodes (`Node`);
  418. this.inodes = {};
  419. // List of released i-node numbers, for reuse.
  420. this.releasedInos = [];
  421. // A mapping for file descriptors to `File`s.
  422. this.fds = {};
  423. // A list of reusable (opened and closed) file descriptors, that should be
  424. // used first before creating a new file descriptor.
  425. this.releasedFds = [];
  426. // Max number of open files.
  427. this.maxFiles = 10000;
  428. // Current number of open files.
  429. this.openFiles = 0;
  430. this.promisesApi = (0, promises_1.createPromisesApi)(this);
  431. this.statWatchers = {};
  432. this.props = Object.assign({ Node: node_1.Node, Link: node_1.Link, File: node_1.File }, props);
  433. const root = this.createLink();
  434. root.setNode(this.createNode(true));
  435. const self = this; // tslint:disable-line no-this-assignment
  436. this.StatWatcher = class extends StatWatcher {
  437. constructor() {
  438. super(self);
  439. }
  440. };
  441. const _ReadStream = FsReadStream;
  442. this.ReadStream = class extends _ReadStream {
  443. constructor(...args) {
  444. super(self, ...args);
  445. }
  446. };
  447. const _WriteStream = FsWriteStream;
  448. this.WriteStream = class extends _WriteStream {
  449. constructor(...args) {
  450. super(self, ...args);
  451. }
  452. };
  453. this.FSWatcher = class extends FSWatcher {
  454. constructor() {
  455. super(self);
  456. }
  457. };
  458. root.setChild('.', root);
  459. root.getNode().nlink++;
  460. root.setChild('..', root);
  461. root.getNode().nlink++;
  462. this.root = root;
  463. }
  464. createLink(parent, name, isDirectory = false, perm) {
  465. if (!parent) {
  466. return new this.props.Link(this, null, '');
  467. }
  468. if (!name) {
  469. throw new Error('createLink: name cannot be empty');
  470. }
  471. return parent.createChild(name, this.createNode(isDirectory, perm));
  472. }
  473. deleteLink(link) {
  474. const parent = link.parent;
  475. if (parent) {
  476. parent.deleteChild(link);
  477. return true;
  478. }
  479. return false;
  480. }
  481. newInoNumber() {
  482. const releasedFd = this.releasedInos.pop();
  483. if (releasedFd)
  484. return releasedFd;
  485. else {
  486. this.ino = (this.ino + 1) % 0xffffffff;
  487. return this.ino;
  488. }
  489. }
  490. newFdNumber() {
  491. const releasedFd = this.releasedFds.pop();
  492. return typeof releasedFd === 'number' ? releasedFd : Volume.fd--;
  493. }
  494. createNode(isDirectory = false, perm) {
  495. const node = new this.props.Node(this.newInoNumber(), perm);
  496. if (isDirectory)
  497. node.setIsDirectory();
  498. this.inodes[node.ino] = node;
  499. return node;
  500. }
  501. getNode(ino) {
  502. return this.inodes[ino];
  503. }
  504. deleteNode(node) {
  505. node.del();
  506. delete this.inodes[node.ino];
  507. this.releasedInos.push(node.ino);
  508. }
  509. // Generates 6 character long random string, used by `mkdtemp`.
  510. genRndStr() {
  511. const str = (Math.random() + 1).toString(36).substring(2, 8);
  512. if (str.length === 6)
  513. return str;
  514. else
  515. return this.genRndStr();
  516. }
  517. // Returns a `Link` (hard link) referenced by path "split" into steps.
  518. getLink(steps) {
  519. return this.root.walk(steps);
  520. }
  521. // Just link `getLink`, but throws a correct user error, if link to found.
  522. getLinkOrThrow(filename, funcName) {
  523. const steps = filenameToSteps(filename);
  524. const link = this.getLink(steps);
  525. if (!link)
  526. throw createError(ENOENT, funcName, filename);
  527. return link;
  528. }
  529. // Just like `getLink`, but also dereference/resolves symbolic links.
  530. getResolvedLink(filenameOrSteps) {
  531. let steps = typeof filenameOrSteps === 'string' ? filenameToSteps(filenameOrSteps) : filenameOrSteps;
  532. let link = this.root;
  533. let i = 0;
  534. while (i < steps.length) {
  535. const step = steps[i];
  536. link = link.getChild(step);
  537. if (!link)
  538. return null;
  539. const node = link.getNode();
  540. if (node.isSymlink()) {
  541. steps = node.symlink.concat(steps.slice(i + 1));
  542. link = this.root;
  543. i = 0;
  544. continue;
  545. }
  546. i++;
  547. }
  548. return link;
  549. }
  550. // Just like `getLinkOrThrow`, but also dereference/resolves symbolic links.
  551. getResolvedLinkOrThrow(filename, funcName) {
  552. const link = this.getResolvedLink(filename);
  553. if (!link)
  554. throw createError(ENOENT, funcName, filename);
  555. return link;
  556. }
  557. resolveSymlinks(link) {
  558. // let node: Node = link.getNode();
  559. // while(link && node.isSymlink()) {
  560. // link = this.getLink(node.symlink);
  561. // if(!link) return null;
  562. // node = link.getNode();
  563. // }
  564. // return link;
  565. return this.getResolvedLink(link.steps.slice(1));
  566. }
  567. // Just like `getLinkOrThrow`, but also verifies that the link is a directory.
  568. getLinkAsDirOrThrow(filename, funcName) {
  569. const link = this.getLinkOrThrow(filename, funcName);
  570. if (!link.getNode().isDirectory())
  571. throw createError(ENOTDIR, funcName, filename);
  572. return link;
  573. }
  574. // Get the immediate parent directory of the link.
  575. getLinkParent(steps) {
  576. return this.root.walk(steps, steps.length - 1);
  577. }
  578. getLinkParentAsDirOrThrow(filenameOrSteps, funcName) {
  579. const steps = filenameOrSteps instanceof Array ? filenameOrSteps : filenameToSteps(filenameOrSteps);
  580. const link = this.getLinkParent(steps);
  581. if (!link)
  582. throw createError(ENOENT, funcName, sep + steps.join(sep));
  583. if (!link.getNode().isDirectory())
  584. throw createError(ENOTDIR, funcName, sep + steps.join(sep));
  585. return link;
  586. }
  587. getFileByFd(fd) {
  588. return this.fds[String(fd)];
  589. }
  590. getFileByFdOrThrow(fd, funcName) {
  591. if (!isFd(fd))
  592. throw TypeError(ERRSTR.FD);
  593. const file = this.getFileByFd(fd);
  594. if (!file)
  595. throw createError(EBADF, funcName);
  596. return file;
  597. }
  598. /**
  599. * @todo This is not used anymore. Remove.
  600. */
  601. /*
  602. private getNodeByIdOrCreate(id: TFileId, flags: number, perm: number): Node {
  603. if (typeof id === 'number') {
  604. const file = this.getFileByFd(id);
  605. if (!file) throw Error('File nto found');
  606. return file.node;
  607. } else {
  608. const steps = pathToSteps(id as PathLike);
  609. let link = this.getLink(steps);
  610. if (link) return link.getNode();
  611. // Try creating a node if not found.
  612. if (flags & O_CREAT) {
  613. const dirLink = this.getLinkParent(steps);
  614. if (dirLink) {
  615. const name = steps[steps.length - 1];
  616. link = this.createLink(dirLink, name, false, perm);
  617. return link.getNode();
  618. }
  619. }
  620. throw createError(ENOENT, 'getNodeByIdOrCreate', pathToFilename(id));
  621. }
  622. }
  623. */
  624. wrapAsync(method, args, callback) {
  625. validateCallback(callback);
  626. (0, setImmediate_1.default)(() => {
  627. let result;
  628. try {
  629. result = method.apply(this, args);
  630. }
  631. catch (err) {
  632. callback(err);
  633. return;
  634. }
  635. callback(null, result);
  636. });
  637. }
  638. _toJSON(link = this.root, json = {}, path) {
  639. let isEmpty = true;
  640. let children = link.children;
  641. if (link.getNode().isFile()) {
  642. children = { [link.getName()]: link.parent.getChild(link.getName()) };
  643. link = link.parent;
  644. }
  645. for (const name in children) {
  646. if (name === '.' || name === '..') {
  647. continue;
  648. }
  649. isEmpty = false;
  650. const child = link.getChild(name);
  651. if (!child) {
  652. throw new Error('_toJSON: unexpected undefined');
  653. }
  654. const node = child.getNode();
  655. if (node.isFile()) {
  656. let filename = child.getPath();
  657. if (path)
  658. filename = relative(path, filename);
  659. json[filename] = node.getString();
  660. }
  661. else if (node.isDirectory()) {
  662. this._toJSON(child, json, path);
  663. }
  664. }
  665. let dirPath = link.getPath();
  666. if (path)
  667. dirPath = relative(path, dirPath);
  668. if (dirPath && isEmpty) {
  669. json[dirPath] = null;
  670. }
  671. return json;
  672. }
  673. toJSON(paths, json = {}, isRelative = false) {
  674. const links = [];
  675. if (paths) {
  676. if (!(paths instanceof Array))
  677. paths = [paths];
  678. for (const path of paths) {
  679. const filename = pathToFilename(path);
  680. const link = this.getResolvedLink(filename);
  681. if (!link)
  682. continue;
  683. links.push(link);
  684. }
  685. }
  686. else {
  687. links.push(this.root);
  688. }
  689. if (!links.length)
  690. return json;
  691. for (const link of links)
  692. this._toJSON(link, json, isRelative ? link.getPath() : '');
  693. return json;
  694. }
  695. // TODO: `cwd` should probably not invoke `process.cwd()`.
  696. fromJSON(json, cwd = process_1.default.cwd()) {
  697. for (let filename in json) {
  698. const data = json[filename];
  699. filename = resolve(filename, cwd);
  700. if (typeof data === 'string') {
  701. const dir = dirname(filename);
  702. this.mkdirpBase(dir, 511 /* MODE.DIR */);
  703. this.writeFileSync(filename, data);
  704. }
  705. else {
  706. this.mkdirpBase(filename, 511 /* MODE.DIR */);
  707. }
  708. }
  709. }
  710. fromNestedJSON(json, cwd) {
  711. this.fromJSON(flattenJSON(json), cwd);
  712. }
  713. reset() {
  714. this.ino = 0;
  715. this.inodes = {};
  716. this.releasedInos = [];
  717. this.fds = {};
  718. this.releasedFds = [];
  719. this.openFiles = 0;
  720. this.root = this.createLink();
  721. this.root.setNode(this.createNode(true));
  722. }
  723. // Legacy interface
  724. mountSync(mountpoint, json) {
  725. this.fromJSON(json, mountpoint);
  726. }
  727. openLink(link, flagsNum, resolveSymlinks = true) {
  728. if (this.openFiles >= this.maxFiles) {
  729. // Too many open files.
  730. throw createError(EMFILE, 'open', link.getPath());
  731. }
  732. // Resolve symlinks.
  733. let realLink = link;
  734. if (resolveSymlinks)
  735. realLink = this.resolveSymlinks(link);
  736. if (!realLink)
  737. throw createError(ENOENT, 'open', link.getPath());
  738. const node = realLink.getNode();
  739. // Check whether node is a directory
  740. if (node.isDirectory()) {
  741. if ((flagsNum & (O_RDONLY | O_RDWR | O_WRONLY)) !== O_RDONLY)
  742. throw createError(EISDIR, 'open', link.getPath());
  743. }
  744. else {
  745. if (flagsNum & O_DIRECTORY)
  746. throw createError(ENOTDIR, 'open', link.getPath());
  747. }
  748. // Check node permissions
  749. if (!(flagsNum & O_WRONLY)) {
  750. if (!node.canRead()) {
  751. throw createError(EACCES, 'open', link.getPath());
  752. }
  753. }
  754. if (flagsNum & O_RDWR) {
  755. }
  756. const file = new this.props.File(link, node, flagsNum, this.newFdNumber());
  757. this.fds[file.fd] = file;
  758. this.openFiles++;
  759. if (flagsNum & O_TRUNC)
  760. file.truncate();
  761. return file;
  762. }
  763. openFile(filename, flagsNum, modeNum, resolveSymlinks = true) {
  764. const steps = filenameToSteps(filename);
  765. let link = resolveSymlinks ? this.getResolvedLink(steps) : this.getLink(steps);
  766. if (link && flagsNum & O_EXCL)
  767. throw createError(EEXIST, 'open', filename);
  768. // Try creating a new file, if it does not exist.
  769. if (!link && flagsNum & O_CREAT) {
  770. // const dirLink: Link = this.getLinkParent(steps);
  771. const dirLink = this.getResolvedLink(steps.slice(0, steps.length - 1));
  772. // if(!dirLink) throw createError(ENOENT, 'open', filename);
  773. if (!dirLink)
  774. throw createError(ENOENT, 'open', sep + steps.join(sep));
  775. if (flagsNum & O_CREAT && typeof modeNum === 'number') {
  776. link = this.createLink(dirLink, steps[steps.length - 1], false, modeNum);
  777. }
  778. }
  779. if (link)
  780. return this.openLink(link, flagsNum, resolveSymlinks);
  781. throw createError(ENOENT, 'open', filename);
  782. }
  783. openBase(filename, flagsNum, modeNum, resolveSymlinks = true) {
  784. const file = this.openFile(filename, flagsNum, modeNum, resolveSymlinks);
  785. if (!file)
  786. throw createError(ENOENT, 'open', filename);
  787. return file.fd;
  788. }
  789. openSync(path, flags, mode = 438 /* MODE.DEFAULT */) {
  790. // Validate (1) mode; (2) path; (3) flags - in that order.
  791. const modeNum = modeToNumber(mode);
  792. const fileName = pathToFilename(path);
  793. const flagsNum = flagsToNumber(flags);
  794. return this.openBase(fileName, flagsNum, modeNum);
  795. }
  796. open(path, flags, a, b) {
  797. let mode = a;
  798. let callback = b;
  799. if (typeof a === 'function') {
  800. mode = 438 /* MODE.DEFAULT */;
  801. callback = a;
  802. }
  803. mode = mode || 438 /* MODE.DEFAULT */;
  804. const modeNum = modeToNumber(mode);
  805. const fileName = pathToFilename(path);
  806. const flagsNum = flagsToNumber(flags);
  807. this.wrapAsync(this.openBase, [fileName, flagsNum, modeNum], callback);
  808. }
  809. closeFile(file) {
  810. if (!this.fds[file.fd])
  811. return;
  812. this.openFiles--;
  813. delete this.fds[file.fd];
  814. this.releasedFds.push(file.fd);
  815. }
  816. closeSync(fd) {
  817. validateFd(fd);
  818. const file = this.getFileByFdOrThrow(fd, 'close');
  819. this.closeFile(file);
  820. }
  821. close(fd, callback) {
  822. validateFd(fd);
  823. this.wrapAsync(this.closeSync, [fd], callback);
  824. }
  825. openFileOrGetById(id, flagsNum, modeNum) {
  826. if (typeof id === 'number') {
  827. const file = this.fds[id];
  828. if (!file)
  829. throw createError(ENOENT);
  830. return file;
  831. }
  832. else {
  833. return this.openFile(pathToFilename(id), flagsNum, modeNum);
  834. }
  835. }
  836. readBase(fd, buffer, offset, length, position) {
  837. const file = this.getFileByFdOrThrow(fd);
  838. return file.read(buffer, Number(offset), Number(length), position);
  839. }
  840. readSync(fd, buffer, offset, length, position) {
  841. validateFd(fd);
  842. return this.readBase(fd, buffer, offset, length, position);
  843. }
  844. read(fd, buffer, offset, length, position, callback) {
  845. validateCallback(callback);
  846. // This `if` branch is from Node.js
  847. if (length === 0) {
  848. return process_1.default.nextTick(() => {
  849. if (callback)
  850. callback(null, 0, buffer);
  851. });
  852. }
  853. (0, setImmediate_1.default)(() => {
  854. try {
  855. const bytes = this.readBase(fd, buffer, offset, length, position);
  856. callback(null, bytes, buffer);
  857. }
  858. catch (err) {
  859. callback(err);
  860. }
  861. });
  862. }
  863. readFileBase(id, flagsNum, encoding) {
  864. let result;
  865. const isUserFd = typeof id === 'number';
  866. const userOwnsFd = isUserFd && isFd(id);
  867. let fd;
  868. if (userOwnsFd)
  869. fd = id;
  870. else {
  871. const filename = pathToFilename(id);
  872. const steps = filenameToSteps(filename);
  873. const link = this.getResolvedLink(steps);
  874. if (link) {
  875. const node = link.getNode();
  876. if (node.isDirectory())
  877. throw createError(EISDIR, 'open', link.getPath());
  878. }
  879. fd = this.openSync(id, flagsNum);
  880. }
  881. try {
  882. result = bufferToEncoding(this.getFileByFdOrThrow(fd).getBuffer(), encoding);
  883. }
  884. finally {
  885. if (!userOwnsFd) {
  886. this.closeSync(fd);
  887. }
  888. }
  889. return result;
  890. }
  891. readFileSync(file, options) {
  892. const opts = getReadFileOptions(options);
  893. const flagsNum = flagsToNumber(opts.flag);
  894. return this.readFileBase(file, flagsNum, opts.encoding);
  895. }
  896. readFile(id, a, b) {
  897. const [opts, callback] = optsAndCbGenerator(getReadFileOptions)(a, b);
  898. const flagsNum = flagsToNumber(opts.flag);
  899. this.wrapAsync(this.readFileBase, [id, flagsNum, opts.encoding], callback);
  900. }
  901. writeBase(fd, buf, offset, length, position) {
  902. const file = this.getFileByFdOrThrow(fd, 'write');
  903. return file.write(buf, offset, length, position);
  904. }
  905. writeSync(fd, a, b, c, d) {
  906. validateFd(fd);
  907. let encoding;
  908. let offset;
  909. let length;
  910. let position;
  911. const isBuffer = typeof a !== 'string';
  912. if (isBuffer) {
  913. offset = (b || 0) | 0;
  914. length = c;
  915. position = d;
  916. }
  917. else {
  918. position = b;
  919. encoding = c;
  920. }
  921. const buf = dataToBuffer(a, encoding);
  922. if (isBuffer) {
  923. if (typeof length === 'undefined') {
  924. length = buf.length;
  925. }
  926. }
  927. else {
  928. offset = 0;
  929. length = buf.length;
  930. }
  931. return this.writeBase(fd, buf, offset, length, position);
  932. }
  933. write(fd, a, b, c, d, e) {
  934. validateFd(fd);
  935. let offset;
  936. let length;
  937. let position;
  938. let encoding;
  939. let callback;
  940. const tipa = typeof a;
  941. const tipb = typeof b;
  942. const tipc = typeof c;
  943. const tipd = typeof d;
  944. if (tipa !== 'string') {
  945. if (tipb === 'function') {
  946. callback = b;
  947. }
  948. else if (tipc === 'function') {
  949. offset = b | 0;
  950. callback = c;
  951. }
  952. else if (tipd === 'function') {
  953. offset = b | 0;
  954. length = c;
  955. callback = d;
  956. }
  957. else {
  958. offset = b | 0;
  959. length = c;
  960. position = d;
  961. callback = e;
  962. }
  963. }
  964. else {
  965. if (tipb === 'function') {
  966. callback = b;
  967. }
  968. else if (tipc === 'function') {
  969. position = b;
  970. callback = c;
  971. }
  972. else if (tipd === 'function') {
  973. position = b;
  974. encoding = c;
  975. callback = d;
  976. }
  977. }
  978. const buf = dataToBuffer(a, encoding);
  979. if (tipa !== 'string') {
  980. if (typeof length === 'undefined')
  981. length = buf.length;
  982. }
  983. else {
  984. offset = 0;
  985. length = buf.length;
  986. }
  987. const cb = validateCallback(callback);
  988. (0, setImmediate_1.default)(() => {
  989. try {
  990. const bytes = this.writeBase(fd, buf, offset, length, position);
  991. if (tipa !== 'string') {
  992. cb(null, bytes, buf);
  993. }
  994. else {
  995. cb(null, bytes, a);
  996. }
  997. }
  998. catch (err) {
  999. cb(err);
  1000. }
  1001. });
  1002. }
  1003. writeFileBase(id, buf, flagsNum, modeNum) {
  1004. // console.log('writeFileBase', id, buf, flagsNum, modeNum);
  1005. // const node = this.getNodeByIdOrCreate(id, flagsNum, modeNum);
  1006. // node.setBuffer(buf);
  1007. const isUserFd = typeof id === 'number';
  1008. let fd;
  1009. if (isUserFd)
  1010. fd = id;
  1011. else {
  1012. fd = this.openBase(pathToFilename(id), flagsNum, modeNum);
  1013. // fd = this.openSync(id as PathLike, flagsNum, modeNum);
  1014. }
  1015. let offset = 0;
  1016. let length = buf.length;
  1017. let position = flagsNum & O_APPEND ? undefined : 0;
  1018. try {
  1019. while (length > 0) {
  1020. const written = this.writeSync(fd, buf, offset, length, position);
  1021. offset += written;
  1022. length -= written;
  1023. if (position !== undefined)
  1024. position += written;
  1025. }
  1026. }
  1027. finally {
  1028. if (!isUserFd)
  1029. this.closeSync(fd);
  1030. }
  1031. }
  1032. writeFileSync(id, data, options) {
  1033. const opts = getWriteFileOptions(options);
  1034. const flagsNum = flagsToNumber(opts.flag);
  1035. const modeNum = modeToNumber(opts.mode);
  1036. const buf = dataToBuffer(data, opts.encoding);
  1037. this.writeFileBase(id, buf, flagsNum, modeNum);
  1038. }
  1039. writeFile(id, data, a, b) {
  1040. let options = a;
  1041. let callback = b;
  1042. if (typeof a === 'function') {
  1043. options = writeFileDefaults;
  1044. callback = a;
  1045. }
  1046. const cb = validateCallback(callback);
  1047. const opts = getWriteFileOptions(options);
  1048. const flagsNum = flagsToNumber(opts.flag);
  1049. const modeNum = modeToNumber(opts.mode);
  1050. const buf = dataToBuffer(data, opts.encoding);
  1051. this.wrapAsync(this.writeFileBase, [id, buf, flagsNum, modeNum], cb);
  1052. }
  1053. linkBase(filename1, filename2) {
  1054. const steps1 = filenameToSteps(filename1);
  1055. const link1 = this.getLink(steps1);
  1056. if (!link1)
  1057. throw createError(ENOENT, 'link', filename1, filename2);
  1058. const steps2 = filenameToSteps(filename2);
  1059. // Check new link directory exists.
  1060. const dir2 = this.getLinkParent(steps2);
  1061. if (!dir2)
  1062. throw createError(ENOENT, 'link', filename1, filename2);
  1063. const name = steps2[steps2.length - 1];
  1064. // Check if new file already exists.
  1065. if (dir2.getChild(name))
  1066. throw createError(EEXIST, 'link', filename1, filename2);
  1067. const node = link1.getNode();
  1068. node.nlink++;
  1069. dir2.createChild(name, node);
  1070. }
  1071. copyFileBase(src, dest, flags) {
  1072. const buf = this.readFileSync(src);
  1073. if (flags & COPYFILE_EXCL) {
  1074. if (this.existsSync(dest)) {
  1075. throw createError(EEXIST, 'copyFile', src, dest);
  1076. }
  1077. }
  1078. if (flags & COPYFILE_FICLONE_FORCE) {
  1079. throw createError(ENOSYS, 'copyFile', src, dest);
  1080. }
  1081. this.writeFileBase(dest, buf, FLAGS.w, 438 /* MODE.DEFAULT */);
  1082. }
  1083. copyFileSync(src, dest, flags) {
  1084. const srcFilename = pathToFilename(src);
  1085. const destFilename = pathToFilename(dest);
  1086. return this.copyFileBase(srcFilename, destFilename, (flags || 0) | 0);
  1087. }
  1088. copyFile(src, dest, a, b) {
  1089. const srcFilename = pathToFilename(src);
  1090. const destFilename = pathToFilename(dest);
  1091. let flags;
  1092. let callback;
  1093. if (typeof a === 'function') {
  1094. flags = 0;
  1095. callback = a;
  1096. }
  1097. else {
  1098. flags = a;
  1099. callback = b;
  1100. }
  1101. validateCallback(callback);
  1102. this.wrapAsync(this.copyFileBase, [srcFilename, destFilename, flags], callback);
  1103. }
  1104. linkSync(existingPath, newPath) {
  1105. const existingPathFilename = pathToFilename(existingPath);
  1106. const newPathFilename = pathToFilename(newPath);
  1107. this.linkBase(existingPathFilename, newPathFilename);
  1108. }
  1109. link(existingPath, newPath, callback) {
  1110. const existingPathFilename = pathToFilename(existingPath);
  1111. const newPathFilename = pathToFilename(newPath);
  1112. this.wrapAsync(this.linkBase, [existingPathFilename, newPathFilename], callback);
  1113. }
  1114. unlinkBase(filename) {
  1115. const steps = filenameToSteps(filename);
  1116. const link = this.getLink(steps);
  1117. if (!link)
  1118. throw createError(ENOENT, 'unlink', filename);
  1119. // TODO: Check if it is file, dir, other...
  1120. if (link.length)
  1121. throw Error('Dir not empty...');
  1122. this.deleteLink(link);
  1123. const node = link.getNode();
  1124. node.nlink--;
  1125. // When all hard links to i-node are deleted, remove the i-node, too.
  1126. if (node.nlink <= 0) {
  1127. this.deleteNode(node);
  1128. }
  1129. }
  1130. unlinkSync(path) {
  1131. const filename = pathToFilename(path);
  1132. this.unlinkBase(filename);
  1133. }
  1134. unlink(path, callback) {
  1135. const filename = pathToFilename(path);
  1136. this.wrapAsync(this.unlinkBase, [filename], callback);
  1137. }
  1138. symlinkBase(targetFilename, pathFilename) {
  1139. const pathSteps = filenameToSteps(pathFilename);
  1140. // Check if directory exists, where we about to create a symlink.
  1141. const dirLink = this.getLinkParent(pathSteps);
  1142. if (!dirLink)
  1143. throw createError(ENOENT, 'symlink', targetFilename, pathFilename);
  1144. const name = pathSteps[pathSteps.length - 1];
  1145. // Check if new file already exists.
  1146. if (dirLink.getChild(name))
  1147. throw createError(EEXIST, 'symlink', targetFilename, pathFilename);
  1148. // Create symlink.
  1149. const symlink = dirLink.createChild(name);
  1150. symlink.getNode().makeSymlink(filenameToSteps(targetFilename));
  1151. return symlink;
  1152. }
  1153. // `type` argument works only on Windows.
  1154. symlinkSync(target, path, type) {
  1155. const targetFilename = pathToFilename(target);
  1156. const pathFilename = pathToFilename(path);
  1157. this.symlinkBase(targetFilename, pathFilename);
  1158. }
  1159. symlink(target, path, a, b) {
  1160. const callback = validateCallback(typeof a === 'function' ? a : b);
  1161. const targetFilename = pathToFilename(target);
  1162. const pathFilename = pathToFilename(path);
  1163. this.wrapAsync(this.symlinkBase, [targetFilename, pathFilename], callback);
  1164. }
  1165. realpathBase(filename, encoding) {
  1166. const steps = filenameToSteps(filename);
  1167. const realLink = this.getResolvedLink(steps);
  1168. if (!realLink)
  1169. throw createError(ENOENT, 'realpath', filename);
  1170. return (0, encoding_1.strToEncoding)(realLink.getPath() || '/', encoding);
  1171. }
  1172. realpathSync(path, options) {
  1173. return this.realpathBase(pathToFilename(path), getRealpathOptions(options).encoding);
  1174. }
  1175. realpath(path, a, b) {
  1176. const [opts, callback] = getRealpathOptsAndCb(a, b);
  1177. const pathFilename = pathToFilename(path);
  1178. this.wrapAsync(this.realpathBase, [pathFilename, opts.encoding], callback);
  1179. }
  1180. lstatBase(filename, bigint = false, throwIfNoEntry = false) {
  1181. const link = this.getLink(filenameToSteps(filename));
  1182. if (link) {
  1183. return Stats_1.default.build(link.getNode(), bigint);
  1184. }
  1185. else if (!throwIfNoEntry) {
  1186. return undefined;
  1187. }
  1188. else {
  1189. throw createError(ENOENT, 'lstat', filename);
  1190. }
  1191. }
  1192. lstatSync(path, options) {
  1193. const { throwIfNoEntry = true, bigint = false } = getStatOptions(options);
  1194. return this.lstatBase(pathToFilename(path), bigint, throwIfNoEntry);
  1195. }
  1196. lstat(path, a, b) {
  1197. const [{ throwIfNoEntry = true, bigint = false }, callback] = getStatOptsAndCb(a, b);
  1198. this.wrapAsync(this.lstatBase, [pathToFilename(path), bigint, throwIfNoEntry], callback);
  1199. }
  1200. statBase(filename, bigint = false, throwIfNoEntry = true) {
  1201. const link = this.getResolvedLink(filenameToSteps(filename));
  1202. if (link) {
  1203. return Stats_1.default.build(link.getNode(), bigint);
  1204. }
  1205. else if (!throwIfNoEntry) {
  1206. return undefined;
  1207. }
  1208. else {
  1209. throw createError(ENOENT, 'stat', filename);
  1210. }
  1211. }
  1212. statSync(path, options) {
  1213. const { bigint = true, throwIfNoEntry = true } = getStatOptions(options);
  1214. return this.statBase(pathToFilename(path), bigint, throwIfNoEntry);
  1215. }
  1216. stat(path, a, b) {
  1217. const [{ bigint = false, throwIfNoEntry = true }, callback] = getStatOptsAndCb(a, b);
  1218. this.wrapAsync(this.statBase, [pathToFilename(path), bigint, throwIfNoEntry], callback);
  1219. }
  1220. fstatBase(fd, bigint = false) {
  1221. const file = this.getFileByFd(fd);
  1222. if (!file)
  1223. throw createError(EBADF, 'fstat');
  1224. return Stats_1.default.build(file.node, bigint);
  1225. }
  1226. fstatSync(fd, options) {
  1227. return this.fstatBase(fd, getStatOptions(options).bigint);
  1228. }
  1229. fstat(fd, a, b) {
  1230. const [opts, callback] = getStatOptsAndCb(a, b);
  1231. this.wrapAsync(this.fstatBase, [fd, opts.bigint], callback);
  1232. }
  1233. renameBase(oldPathFilename, newPathFilename) {
  1234. const link = this.getLink(filenameToSteps(oldPathFilename));
  1235. if (!link)
  1236. throw createError(ENOENT, 'rename', oldPathFilename, newPathFilename);
  1237. // TODO: Check if it is directory, if non-empty, we cannot move it, right?
  1238. const newPathSteps = filenameToSteps(newPathFilename);
  1239. // Check directory exists for the new location.
  1240. const newPathDirLink = this.getLinkParent(newPathSteps);
  1241. if (!newPathDirLink)
  1242. throw createError(ENOENT, 'rename', oldPathFilename, newPathFilename);
  1243. // TODO: Also treat cases with directories and symbolic links.
  1244. // TODO: See: http://man7.org/linux/man-pages/man2/rename.2.html
  1245. // Remove hard link from old folder.
  1246. const oldLinkParent = link.parent;
  1247. if (oldLinkParent) {
  1248. oldLinkParent.deleteChild(link);
  1249. }
  1250. // Rename should overwrite the new path, if that exists.
  1251. const name = newPathSteps[newPathSteps.length - 1];
  1252. link.name = name;
  1253. link.steps = [...newPathDirLink.steps, name];
  1254. newPathDirLink.setChild(link.getName(), link);
  1255. }
  1256. renameSync(oldPath, newPath) {
  1257. const oldPathFilename = pathToFilename(oldPath);
  1258. const newPathFilename = pathToFilename(newPath);
  1259. this.renameBase(oldPathFilename, newPathFilename);
  1260. }
  1261. rename(oldPath, newPath, callback) {
  1262. const oldPathFilename = pathToFilename(oldPath);
  1263. const newPathFilename = pathToFilename(newPath);
  1264. this.wrapAsync(this.renameBase, [oldPathFilename, newPathFilename], callback);
  1265. }
  1266. existsBase(filename) {
  1267. return !!this.statBase(filename);
  1268. }
  1269. existsSync(path) {
  1270. try {
  1271. return this.existsBase(pathToFilename(path));
  1272. }
  1273. catch (err) {
  1274. return false;
  1275. }
  1276. }
  1277. exists(path, callback) {
  1278. const filename = pathToFilename(path);
  1279. if (typeof callback !== 'function')
  1280. throw Error(ERRSTR.CB);
  1281. (0, setImmediate_1.default)(() => {
  1282. try {
  1283. callback(this.existsBase(filename));
  1284. }
  1285. catch (err) {
  1286. callback(false);
  1287. }
  1288. });
  1289. }
  1290. accessBase(filename, mode) {
  1291. const link = this.getLinkOrThrow(filename, 'access');
  1292. // TODO: Verify permissions
  1293. }
  1294. accessSync(path, mode = F_OK) {
  1295. const filename = pathToFilename(path);
  1296. mode = mode | 0;
  1297. this.accessBase(filename, mode);
  1298. }
  1299. access(path, a, b) {
  1300. let mode = F_OK;
  1301. let callback;
  1302. if (typeof a !== 'function') {
  1303. mode = a | 0; // cast to number
  1304. callback = validateCallback(b);
  1305. }
  1306. else {
  1307. callback = a;
  1308. }
  1309. const filename = pathToFilename(path);
  1310. this.wrapAsync(this.accessBase, [filename, mode], callback);
  1311. }
  1312. appendFileSync(id, data, options = appendFileDefaults) {
  1313. const opts = getAppendFileOpts(options);
  1314. // force append behavior when using a supplied file descriptor
  1315. if (!opts.flag || isFd(id))
  1316. opts.flag = 'a';
  1317. this.writeFileSync(id, data, opts);
  1318. }
  1319. appendFile(id, data, a, b) {
  1320. const [opts, callback] = getAppendFileOptsAndCb(a, b);
  1321. // force append behavior when using a supplied file descriptor
  1322. if (!opts.flag || isFd(id))
  1323. opts.flag = 'a';
  1324. this.writeFile(id, data, opts, callback);
  1325. }
  1326. readdirBase(filename, options) {
  1327. const steps = filenameToSteps(filename);
  1328. const link = this.getResolvedLink(steps);
  1329. if (!link)
  1330. throw createError(ENOENT, 'readdir', filename);
  1331. const node = link.getNode();
  1332. if (!node.isDirectory())
  1333. throw createError(ENOTDIR, 'scandir', filename);
  1334. if (options.withFileTypes) {
  1335. const list = [];
  1336. for (const name in link.children) {
  1337. const child = link.getChild(name);
  1338. if (!child || name === '.' || name === '..') {
  1339. continue;
  1340. }
  1341. list.push(Dirent_1.default.build(child, options.encoding));
  1342. }
  1343. if (!isWin && options.encoding !== 'buffer')
  1344. list.sort((a, b) => {
  1345. if (a.name < b.name)
  1346. return -1;
  1347. if (a.name > b.name)
  1348. return 1;
  1349. return 0;
  1350. });
  1351. return list;
  1352. }
  1353. const list = [];
  1354. for (const name in link.children) {
  1355. if (name === '.' || name === '..') {
  1356. continue;
  1357. }
  1358. list.push((0, encoding_1.strToEncoding)(name, options.encoding));
  1359. }
  1360. if (!isWin && options.encoding !== 'buffer')
  1361. list.sort();
  1362. return list;
  1363. }
  1364. readdirSync(path, options) {
  1365. const opts = getReaddirOptions(options);
  1366. const filename = pathToFilename(path);
  1367. return this.readdirBase(filename, opts);
  1368. }
  1369. readdir(path, a, b) {
  1370. const [options, callback] = getReaddirOptsAndCb(a, b);
  1371. const filename = pathToFilename(path);
  1372. this.wrapAsync(this.readdirBase, [filename, options], callback);
  1373. }
  1374. readlinkBase(filename, encoding) {
  1375. const link = this.getLinkOrThrow(filename, 'readlink');
  1376. const node = link.getNode();
  1377. if (!node.isSymlink())
  1378. throw createError(EINVAL, 'readlink', filename);
  1379. const str = sep + node.symlink.join(sep);
  1380. return (0, encoding_1.strToEncoding)(str, encoding);
  1381. }
  1382. readlinkSync(path, options) {
  1383. const opts = getDefaultOpts(options);
  1384. const filename = pathToFilename(path);
  1385. return this.readlinkBase(filename, opts.encoding);
  1386. }
  1387. readlink(path, a, b) {
  1388. const [opts, callback] = getDefaultOptsAndCb(a, b);
  1389. const filename = pathToFilename(path);
  1390. this.wrapAsync(this.readlinkBase, [filename, opts.encoding], callback);
  1391. }
  1392. fsyncBase(fd) {
  1393. this.getFileByFdOrThrow(fd, 'fsync');
  1394. }
  1395. fsyncSync(fd) {
  1396. this.fsyncBase(fd);
  1397. }
  1398. fsync(fd, callback) {
  1399. this.wrapAsync(this.fsyncBase, [fd], callback);
  1400. }
  1401. fdatasyncBase(fd) {
  1402. this.getFileByFdOrThrow(fd, 'fdatasync');
  1403. }
  1404. fdatasyncSync(fd) {
  1405. this.fdatasyncBase(fd);
  1406. }
  1407. fdatasync(fd, callback) {
  1408. this.wrapAsync(this.fdatasyncBase, [fd], callback);
  1409. }
  1410. ftruncateBase(fd, len) {
  1411. const file = this.getFileByFdOrThrow(fd, 'ftruncate');
  1412. file.truncate(len);
  1413. }
  1414. ftruncateSync(fd, len) {
  1415. this.ftruncateBase(fd, len);
  1416. }
  1417. ftruncate(fd, a, b) {
  1418. const len = typeof a === 'number' ? a : 0;
  1419. const callback = validateCallback(typeof a === 'number' ? b : a);
  1420. this.wrapAsync(this.ftruncateBase, [fd, len], callback);
  1421. }
  1422. truncateBase(path, len) {
  1423. const fd = this.openSync(path, 'r+');
  1424. try {
  1425. this.ftruncateSync(fd, len);
  1426. }
  1427. finally {
  1428. this.closeSync(fd);
  1429. }
  1430. }
  1431. truncateSync(id, len) {
  1432. if (isFd(id))
  1433. return this.ftruncateSync(id, len);
  1434. this.truncateBase(id, len);
  1435. }
  1436. truncate(id, a, b) {
  1437. const len = typeof a === 'number' ? a : 0;
  1438. const callback = validateCallback(typeof a === 'number' ? b : a);
  1439. if (isFd(id))
  1440. return this.ftruncate(id, len, callback);
  1441. this.wrapAsync(this.truncateBase, [id, len], callback);
  1442. }
  1443. futimesBase(fd, atime, mtime) {
  1444. const file = this.getFileByFdOrThrow(fd, 'futimes');
  1445. const node = file.node;
  1446. node.atime = new Date(atime * 1000);
  1447. node.mtime = new Date(mtime * 1000);
  1448. }
  1449. futimesSync(fd, atime, mtime) {
  1450. this.futimesBase(fd, toUnixTimestamp(atime), toUnixTimestamp(mtime));
  1451. }
  1452. futimes(fd, atime, mtime, callback) {
  1453. this.wrapAsync(this.futimesBase, [fd, toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback);
  1454. }
  1455. utimesBase(filename, atime, mtime) {
  1456. const fd = this.openSync(filename, 'r');
  1457. try {
  1458. this.futimesBase(fd, atime, mtime);
  1459. }
  1460. finally {
  1461. this.closeSync(fd);
  1462. }
  1463. }
  1464. utimesSync(path, atime, mtime) {
  1465. this.utimesBase(pathToFilename(path), toUnixTimestamp(atime), toUnixTimestamp(mtime));
  1466. }
  1467. utimes(path, atime, mtime, callback) {
  1468. this.wrapAsync(this.utimesBase, [pathToFilename(path), toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback);
  1469. }
  1470. mkdirBase(filename, modeNum) {
  1471. const steps = filenameToSteps(filename);
  1472. // This will throw if user tries to create root dir `fs.mkdirSync('/')`.
  1473. if (!steps.length) {
  1474. throw createError(EEXIST, 'mkdir', filename);
  1475. }
  1476. const dir = this.getLinkParentAsDirOrThrow(filename, 'mkdir');
  1477. // Check path already exists.
  1478. const name = steps[steps.length - 1];
  1479. if (dir.getChild(name))
  1480. throw createError(EEXIST, 'mkdir', filename);
  1481. dir.createChild(name, this.createNode(true, modeNum));
  1482. }
  1483. /**
  1484. * Creates directory tree recursively.
  1485. * @param filename
  1486. * @param modeNum
  1487. */
  1488. mkdirpBase(filename, modeNum) {
  1489. const fullPath = resolve(filename);
  1490. const fullPathSansSlash = fullPath.substring(1);
  1491. const steps = !fullPathSansSlash ? [] : fullPathSansSlash.split(sep);
  1492. let link = this.root;
  1493. let created = false;
  1494. for (let i = 0; i < steps.length; i++) {
  1495. const step = steps[i];
  1496. if (!link.getNode().isDirectory())
  1497. throw createError(ENOTDIR, 'mkdir', link.getPath());
  1498. const child = link.getChild(step);
  1499. if (child) {
  1500. if (child.getNode().isDirectory())
  1501. link = child;
  1502. else
  1503. throw createError(ENOTDIR, 'mkdir', child.getPath());
  1504. }
  1505. else {
  1506. link = link.createChild(step, this.createNode(true, modeNum));
  1507. created = true;
  1508. }
  1509. }
  1510. return created ? fullPath : undefined;
  1511. }
  1512. mkdirSync(path, options) {
  1513. const opts = getMkdirOptions(options);
  1514. const modeNum = modeToNumber(opts.mode, 0o777);
  1515. const filename = pathToFilename(path);
  1516. if (opts.recursive)
  1517. return this.mkdirpBase(filename, modeNum);
  1518. this.mkdirBase(filename, modeNum);
  1519. }
  1520. mkdir(path, a, b) {
  1521. const opts = getMkdirOptions(a);
  1522. const callback = validateCallback(typeof a === 'function' ? a : b);
  1523. const modeNum = modeToNumber(opts.mode, 0o777);
  1524. const filename = pathToFilename(path);
  1525. if (opts.recursive)
  1526. this.wrapAsync(this.mkdirpBase, [filename, modeNum], callback);
  1527. else
  1528. this.wrapAsync(this.mkdirBase, [filename, modeNum], callback);
  1529. }
  1530. // legacy interface
  1531. mkdirpSync(path, mode) {
  1532. return this.mkdirSync(path, { mode, recursive: true });
  1533. }
  1534. mkdirp(path, a, b) {
  1535. const mode = typeof a === 'function' ? undefined : a;
  1536. const callback = validateCallback(typeof a === 'function' ? a : b);
  1537. this.mkdir(path, { mode, recursive: true }, callback);
  1538. }
  1539. mkdtempBase(prefix, encoding, retry = 5) {
  1540. const filename = prefix + this.genRndStr();
  1541. try {
  1542. this.mkdirBase(filename, 511 /* MODE.DIR */);
  1543. return (0, encoding_1.strToEncoding)(filename, encoding);
  1544. }
  1545. catch (err) {
  1546. if (err.code === EEXIST) {
  1547. if (retry > 1)
  1548. return this.mkdtempBase(prefix, encoding, retry - 1);
  1549. else
  1550. throw Error('Could not create temp dir.');
  1551. }
  1552. else
  1553. throw err;
  1554. }
  1555. }
  1556. mkdtempSync(prefix, options) {
  1557. const { encoding } = getDefaultOpts(options);
  1558. if (!prefix || typeof prefix !== 'string')
  1559. throw new TypeError('filename prefix is required');
  1560. nullCheck(prefix);
  1561. return this.mkdtempBase(prefix, encoding);
  1562. }
  1563. mkdtemp(prefix, a, b) {
  1564. const [{ encoding }, callback] = getDefaultOptsAndCb(a, b);
  1565. if (!prefix || typeof prefix !== 'string')
  1566. throw new TypeError('filename prefix is required');
  1567. if (!nullCheck(prefix))
  1568. return;
  1569. this.wrapAsync(this.mkdtempBase, [prefix, encoding], callback);
  1570. }
  1571. rmdirBase(filename, options) {
  1572. const opts = getRmdirOptions(options);
  1573. const link = this.getLinkAsDirOrThrow(filename, 'rmdir');
  1574. // Check directory is empty.
  1575. if (link.length && !opts.recursive)
  1576. throw createError(ENOTEMPTY, 'rmdir', filename);
  1577. this.deleteLink(link);
  1578. }
  1579. rmdirSync(path, options) {
  1580. this.rmdirBase(pathToFilename(path), options);
  1581. }
  1582. rmdir(path, a, b) {
  1583. const opts = getRmdirOptions(a);
  1584. const callback = validateCallback(typeof a === 'function' ? a : b);
  1585. this.wrapAsync(this.rmdirBase, [pathToFilename(path), opts], callback);
  1586. }
  1587. rmBase(filename, options = {}) {
  1588. const link = this.getResolvedLink(filename);
  1589. if (!link) {
  1590. // "stat" is used to match Node's native error message.
  1591. if (!options.force)
  1592. throw createError(ENOENT, 'stat', filename);
  1593. return;
  1594. }
  1595. if (link.getNode().isDirectory()) {
  1596. if (!options.recursive) {
  1597. throw createError(ERR_FS_EISDIR, 'rm', filename);
  1598. }
  1599. }
  1600. this.deleteLink(link);
  1601. }
  1602. rmSync(path, options) {
  1603. this.rmBase(pathToFilename(path), options);
  1604. }
  1605. rm(path, a, b) {
  1606. const [opts, callback] = getRmOptsAndCb(a, b);
  1607. this.wrapAsync(this.rmBase, [pathToFilename(path), opts], callback);
  1608. }
  1609. fchmodBase(fd, modeNum) {
  1610. const file = this.getFileByFdOrThrow(fd, 'fchmod');
  1611. file.chmod(modeNum);
  1612. }
  1613. fchmodSync(fd, mode) {
  1614. this.fchmodBase(fd, modeToNumber(mode));
  1615. }
  1616. fchmod(fd, mode, callback) {
  1617. this.wrapAsync(this.fchmodBase, [fd, modeToNumber(mode)], callback);
  1618. }
  1619. chmodBase(filename, modeNum) {
  1620. const fd = this.openSync(filename, 'r');
  1621. try {
  1622. this.fchmodBase(fd, modeNum);
  1623. }
  1624. finally {
  1625. this.closeSync(fd);
  1626. }
  1627. }
  1628. chmodSync(path, mode) {
  1629. const modeNum = modeToNumber(mode);
  1630. const filename = pathToFilename(path);
  1631. this.chmodBase(filename, modeNum);
  1632. }
  1633. chmod(path, mode, callback) {
  1634. const modeNum = modeToNumber(mode);
  1635. const filename = pathToFilename(path);
  1636. this.wrapAsync(this.chmodBase, [filename, modeNum], callback);
  1637. }
  1638. lchmodBase(filename, modeNum) {
  1639. const fd = this.openBase(filename, O_RDWR, 0, false);
  1640. try {
  1641. this.fchmodBase(fd, modeNum);
  1642. }
  1643. finally {
  1644. this.closeSync(fd);
  1645. }
  1646. }
  1647. lchmodSync(path, mode) {
  1648. const modeNum = modeToNumber(mode);
  1649. const filename = pathToFilename(path);
  1650. this.lchmodBase(filename, modeNum);
  1651. }
  1652. lchmod(path, mode, callback) {
  1653. const modeNum = modeToNumber(mode);
  1654. const filename = pathToFilename(path);
  1655. this.wrapAsync(this.lchmodBase, [filename, modeNum], callback);
  1656. }
  1657. fchownBase(fd, uid, gid) {
  1658. this.getFileByFdOrThrow(fd, 'fchown').chown(uid, gid);
  1659. }
  1660. fchownSync(fd, uid, gid) {
  1661. validateUid(uid);
  1662. validateGid(gid);
  1663. this.fchownBase(fd, uid, gid);
  1664. }
  1665. fchown(fd, uid, gid, callback) {
  1666. validateUid(uid);
  1667. validateGid(gid);
  1668. this.wrapAsync(this.fchownBase, [fd, uid, gid], callback);
  1669. }
  1670. chownBase(filename, uid, gid) {
  1671. const link = this.getResolvedLinkOrThrow(filename, 'chown');
  1672. const node = link.getNode();
  1673. node.chown(uid, gid);
  1674. // if(node.isFile() || node.isSymlink()) {
  1675. //
  1676. // } else if(node.isDirectory()) {
  1677. //
  1678. // } else {
  1679. // TODO: What do we do here?
  1680. // }
  1681. }
  1682. chownSync(path, uid, gid) {
  1683. validateUid(uid);
  1684. validateGid(gid);
  1685. this.chownBase(pathToFilename(path), uid, gid);
  1686. }
  1687. chown(path, uid, gid, callback) {
  1688. validateUid(uid);
  1689. validateGid(gid);
  1690. this.wrapAsync(this.chownBase, [pathToFilename(path), uid, gid], callback);
  1691. }
  1692. lchownBase(filename, uid, gid) {
  1693. this.getLinkOrThrow(filename, 'lchown').getNode().chown(uid, gid);
  1694. }
  1695. lchownSync(path, uid, gid) {
  1696. validateUid(uid);
  1697. validateGid(gid);
  1698. this.lchownBase(pathToFilename(path), uid, gid);
  1699. }
  1700. lchown(path, uid, gid, callback) {
  1701. validateUid(uid);
  1702. validateGid(gid);
  1703. this.wrapAsync(this.lchownBase, [pathToFilename(path), uid, gid], callback);
  1704. }
  1705. watchFile(path, a, b) {
  1706. const filename = pathToFilename(path);
  1707. let options = a;
  1708. let listener = b;
  1709. if (typeof options === 'function') {
  1710. listener = a;
  1711. options = null;
  1712. }
  1713. if (typeof listener !== 'function') {
  1714. throw Error('"watchFile()" requires a listener function');
  1715. }
  1716. let interval = 5007;
  1717. let persistent = true;
  1718. if (options && typeof options === 'object') {
  1719. if (typeof options.interval === 'number')
  1720. interval = options.interval;
  1721. if (typeof options.persistent === 'boolean')
  1722. persistent = options.persistent;
  1723. }
  1724. let watcher = this.statWatchers[filename];
  1725. if (!watcher) {
  1726. watcher = new this.StatWatcher();
  1727. watcher.start(filename, persistent, interval);
  1728. this.statWatchers[filename] = watcher;
  1729. }
  1730. watcher.addListener('change', listener);
  1731. return watcher;
  1732. }
  1733. unwatchFile(path, listener) {
  1734. const filename = pathToFilename(path);
  1735. const watcher = this.statWatchers[filename];
  1736. if (!watcher)
  1737. return;
  1738. if (typeof listener === 'function') {
  1739. watcher.removeListener('change', listener);
  1740. }
  1741. else {
  1742. watcher.removeAllListeners('change');
  1743. }
  1744. if (watcher.listenerCount('change') === 0) {
  1745. watcher.stop();
  1746. delete this.statWatchers[filename];
  1747. }
  1748. }
  1749. createReadStream(path, options) {
  1750. return new this.ReadStream(path, options);
  1751. }
  1752. createWriteStream(path, options) {
  1753. return new this.WriteStream(path, options);
  1754. }
  1755. // watch(path: PathLike): FSWatcher;
  1756. // watch(path: PathLike, options?: IWatchOptions | string): FSWatcher;
  1757. watch(path, options, listener) {
  1758. const filename = pathToFilename(path);
  1759. let givenOptions = options;
  1760. if (typeof options === 'function') {
  1761. listener = options;
  1762. givenOptions = null;
  1763. }
  1764. // tslint:disable-next-line prefer-const
  1765. let { persistent, recursive, encoding } = getDefaultOpts(givenOptions);
  1766. if (persistent === undefined)
  1767. persistent = true;
  1768. if (recursive === undefined)
  1769. recursive = false;
  1770. const watcher = new this.FSWatcher();
  1771. watcher.start(filename, persistent, recursive, encoding);
  1772. if (listener) {
  1773. watcher.addListener('change', listener);
  1774. }
  1775. return watcher;
  1776. }
  1777. }
  1778. exports.Volume = Volume;
  1779. /**
  1780. * Global file descriptor counter. UNIX file descriptors start from 0 and go sequentially
  1781. * up, so here, in order not to conflict with them, we choose some big number and descrease
  1782. * the file descriptor of every new opened file.
  1783. * @type {number}
  1784. * @todo This should not be static, right?
  1785. */
  1786. Volume.fd = 0x7fffffff;
  1787. function emitStop(self) {
  1788. self.emit('stop');
  1789. }
  1790. class StatWatcher extends events_1.EventEmitter {
  1791. constructor(vol) {
  1792. super();
  1793. this.onInterval = () => {
  1794. try {
  1795. const stats = this.vol.statSync(this.filename);
  1796. if (this.hasChanged(stats)) {
  1797. this.emit('change', stats, this.prev);
  1798. this.prev = stats;
  1799. }
  1800. }
  1801. finally {
  1802. this.loop();
  1803. }
  1804. };
  1805. this.vol = vol;
  1806. }
  1807. loop() {
  1808. this.timeoutRef = this.setTimeout(this.onInterval, this.interval);
  1809. }
  1810. hasChanged(stats) {
  1811. // if(!this.prev) return false;
  1812. if (stats.mtimeMs > this.prev.mtimeMs)
  1813. return true;
  1814. if (stats.nlink !== this.prev.nlink)
  1815. return true;
  1816. return false;
  1817. }
  1818. start(path, persistent = true, interval = 5007) {
  1819. this.filename = pathToFilename(path);
  1820. this.setTimeout = persistent
  1821. ? setTimeout.bind(typeof globalThis !== 'undefined' ? globalThis : global)
  1822. : setTimeoutUnref_1.default;
  1823. this.interval = interval;
  1824. this.prev = this.vol.statSync(this.filename);
  1825. this.loop();
  1826. }
  1827. stop() {
  1828. clearTimeout(this.timeoutRef);
  1829. process_1.default.nextTick(emitStop, this);
  1830. }
  1831. }
  1832. exports.StatWatcher = StatWatcher;
  1833. var pool;
  1834. function allocNewPool(poolSize) {
  1835. pool = (0, buffer_1.bufferAllocUnsafe)(poolSize);
  1836. pool.used = 0;
  1837. }
  1838. util.inherits(FsReadStream, stream_1.Readable);
  1839. exports.ReadStream = FsReadStream;
  1840. function FsReadStream(vol, path, options) {
  1841. if (!(this instanceof FsReadStream))
  1842. return new FsReadStream(vol, path, options);
  1843. this._vol = vol;
  1844. // a little bit bigger buffer and water marks by default
  1845. options = Object.assign({}, getOptions(options, {}));
  1846. if (options.highWaterMark === undefined)
  1847. options.highWaterMark = 64 * 1024;
  1848. stream_1.Readable.call(this, options);
  1849. this.path = pathToFilename(path);
  1850. this.fd = options.fd === undefined ? null : options.fd;
  1851. this.flags = options.flags === undefined ? 'r' : options.flags;
  1852. this.mode = options.mode === undefined ? 0o666 : options.mode;
  1853. this.start = options.start;
  1854. this.end = options.end;
  1855. this.autoClose = options.autoClose === undefined ? true : options.autoClose;
  1856. this.pos = undefined;
  1857. this.bytesRead = 0;
  1858. if (this.start !== undefined) {
  1859. if (typeof this.start !== 'number') {
  1860. throw new TypeError('"start" option must be a Number');
  1861. }
  1862. if (this.end === undefined) {
  1863. this.end = Infinity;
  1864. }
  1865. else if (typeof this.end !== 'number') {
  1866. throw new TypeError('"end" option must be a Number');
  1867. }
  1868. if (this.start > this.end) {
  1869. throw new Error('"start" option must be <= "end" option');
  1870. }
  1871. this.pos = this.start;
  1872. }
  1873. if (typeof this.fd !== 'number')
  1874. this.open();
  1875. this.on('end', function () {
  1876. if (this.autoClose) {
  1877. if (this.destroy)
  1878. this.destroy();
  1879. }
  1880. });
  1881. }
  1882. FsReadStream.prototype.open = function () {
  1883. var self = this; // tslint:disable-line no-this-assignment
  1884. this._vol.open(this.path, this.flags, this.mode, (er, fd) => {
  1885. if (er) {
  1886. if (self.autoClose) {
  1887. if (self.destroy)
  1888. self.destroy();
  1889. }
  1890. self.emit('error', er);
  1891. return;
  1892. }
  1893. self.fd = fd;
  1894. self.emit('open', fd);
  1895. // start the flow of data.
  1896. self.read();
  1897. });
  1898. };
  1899. FsReadStream.prototype._read = function (n) {
  1900. if (typeof this.fd !== 'number') {
  1901. return this.once('open', function () {
  1902. this._read(n);
  1903. });
  1904. }
  1905. if (this.destroyed)
  1906. return;
  1907. if (!pool || pool.length - pool.used < kMinPoolSpace) {
  1908. // discard the old pool.
  1909. allocNewPool(this._readableState.highWaterMark);
  1910. }
  1911. // Grab another reference to the pool in the case that while we're
  1912. // in the thread pool another read() finishes up the pool, and
  1913. // allocates a new one.
  1914. var thisPool = pool;
  1915. var toRead = Math.min(pool.length - pool.used, n);
  1916. var start = pool.used;
  1917. if (this.pos !== undefined)
  1918. toRead = Math.min(this.end - this.pos + 1, toRead);
  1919. // already read everything we were supposed to read!
  1920. // treat as EOF.
  1921. if (toRead <= 0)
  1922. return this.push(null);
  1923. // the actual read.
  1924. var self = this; // tslint:disable-line no-this-assignment
  1925. this._vol.read(this.fd, pool, pool.used, toRead, this.pos, onread);
  1926. // move the pool positions, and internal position for reading.
  1927. if (this.pos !== undefined)
  1928. this.pos += toRead;
  1929. pool.used += toRead;
  1930. function onread(er, bytesRead) {
  1931. if (er) {
  1932. if (self.autoClose && self.destroy) {
  1933. self.destroy();
  1934. }
  1935. self.emit('error', er);
  1936. }
  1937. else {
  1938. var b = null;
  1939. if (bytesRead > 0) {
  1940. self.bytesRead += bytesRead;
  1941. b = thisPool.slice(start, start + bytesRead);
  1942. }
  1943. self.push(b);
  1944. }
  1945. }
  1946. };
  1947. FsReadStream.prototype._destroy = function (err, cb) {
  1948. this.close(err2 => {
  1949. cb(err || err2);
  1950. });
  1951. };
  1952. FsReadStream.prototype.close = function (cb) {
  1953. var _a;
  1954. if (cb)
  1955. this.once('close', cb);
  1956. if (this.closed || typeof this.fd !== 'number') {
  1957. if (typeof this.fd !== 'number') {
  1958. this.once('open', closeOnOpen);
  1959. return;
  1960. }
  1961. return process_1.default.nextTick(() => this.emit('close'));
  1962. }
  1963. // Since Node 18, there is only a getter for '.closed'.
  1964. // The first branch mimics other setters from Readable.
  1965. // See https://github.com/nodejs/node/blob/v18.0.0/lib/internal/streams/readable.js#L1243
  1966. if (typeof ((_a = this._readableState) === null || _a === void 0 ? void 0 : _a.closed) === 'boolean') {
  1967. this._readableState.closed = true;
  1968. }
  1969. else {
  1970. this.closed = true;
  1971. }
  1972. this._vol.close(this.fd, er => {
  1973. if (er)
  1974. this.emit('error', er);
  1975. else
  1976. this.emit('close');
  1977. });
  1978. this.fd = null;
  1979. };
  1980. // needed because as it will be called with arguments
  1981. // that does not match this.close() signature
  1982. function closeOnOpen(fd) {
  1983. this.close();
  1984. }
  1985. util.inherits(FsWriteStream, stream_1.Writable);
  1986. exports.WriteStream = FsWriteStream;
  1987. function FsWriteStream(vol, path, options) {
  1988. if (!(this instanceof FsWriteStream))
  1989. return new FsWriteStream(vol, path, options);
  1990. this._vol = vol;
  1991. options = Object.assign({}, getOptions(options, {}));
  1992. stream_1.Writable.call(this, options);
  1993. this.path = pathToFilename(path);
  1994. this.fd = options.fd === undefined ? null : options.fd;
  1995. this.flags = options.flags === undefined ? 'w' : options.flags;
  1996. this.mode = options.mode === undefined ? 0o666 : options.mode;
  1997. this.start = options.start;
  1998. this.autoClose = options.autoClose === undefined ? true : !!options.autoClose;
  1999. this.pos = undefined;
  2000. this.bytesWritten = 0;
  2001. if (this.start !== undefined) {
  2002. if (typeof this.start !== 'number') {
  2003. throw new TypeError('"start" option must be a Number');
  2004. }
  2005. if (this.start < 0) {
  2006. throw new Error('"start" must be >= zero');
  2007. }
  2008. this.pos = this.start;
  2009. }
  2010. if (options.encoding)
  2011. this.setDefaultEncoding(options.encoding);
  2012. if (typeof this.fd !== 'number')
  2013. this.open();
  2014. // dispose on finish.
  2015. this.once('finish', function () {
  2016. if (this.autoClose) {
  2017. this.close();
  2018. }
  2019. });
  2020. }
  2021. FsWriteStream.prototype.open = function () {
  2022. this._vol.open(this.path, this.flags, this.mode, function (er, fd) {
  2023. if (er) {
  2024. if (this.autoClose && this.destroy) {
  2025. this.destroy();
  2026. }
  2027. this.emit('error', er);
  2028. return;
  2029. }
  2030. this.fd = fd;
  2031. this.emit('open', fd);
  2032. }.bind(this));
  2033. };
  2034. FsWriteStream.prototype._write = function (data, encoding, cb) {
  2035. if (!(data instanceof buffer_1.Buffer || data instanceof Uint8Array))
  2036. return this.emit('error', new Error('Invalid data'));
  2037. if (typeof this.fd !== 'number') {
  2038. return this.once('open', function () {
  2039. this._write(data, encoding, cb);
  2040. });
  2041. }
  2042. var self = this; // tslint:disable-line no-this-assignment
  2043. this._vol.write(this.fd, data, 0, data.length, this.pos, (er, bytes) => {
  2044. if (er) {
  2045. if (self.autoClose && self.destroy) {
  2046. self.destroy();
  2047. }
  2048. return cb(er);
  2049. }
  2050. self.bytesWritten += bytes;
  2051. cb();
  2052. });
  2053. if (this.pos !== undefined)
  2054. this.pos += data.length;
  2055. };
  2056. FsWriteStream.prototype._writev = function (data, cb) {
  2057. if (typeof this.fd !== 'number') {
  2058. return this.once('open', function () {
  2059. this._writev(data, cb);
  2060. });
  2061. }
  2062. const self = this; // tslint:disable-line no-this-assignment
  2063. const len = data.length;
  2064. const chunks = new Array(len);
  2065. var size = 0;
  2066. for (var i = 0; i < len; i++) {
  2067. var chunk = data[i].chunk;
  2068. chunks[i] = chunk;
  2069. size += chunk.length;
  2070. }
  2071. const buf = buffer_1.Buffer.concat(chunks);
  2072. this._vol.write(this.fd, buf, 0, buf.length, this.pos, (er, bytes) => {
  2073. if (er) {
  2074. if (self.destroy)
  2075. self.destroy();
  2076. return cb(er);
  2077. }
  2078. self.bytesWritten += bytes;
  2079. cb();
  2080. });
  2081. if (this.pos !== undefined)
  2082. this.pos += size;
  2083. };
  2084. FsWriteStream.prototype.close = function (cb) {
  2085. var _a;
  2086. if (cb)
  2087. this.once('close', cb);
  2088. if (this.closed || typeof this.fd !== 'number') {
  2089. if (typeof this.fd !== 'number') {
  2090. this.once('open', closeOnOpen);
  2091. return;
  2092. }
  2093. return process_1.default.nextTick(() => this.emit('close'));
  2094. }
  2095. // Since Node 18, there is only a getter for '.closed'.
  2096. // The first branch mimics other setters from Writable.
  2097. // See https://github.com/nodejs/node/blob/v18.0.0/lib/internal/streams/writable.js#L766
  2098. if (typeof ((_a = this._writableState) === null || _a === void 0 ? void 0 : _a.closed) === 'boolean') {
  2099. this._writableState.closed = true;
  2100. }
  2101. else {
  2102. this.closed = true;
  2103. }
  2104. this._vol.close(this.fd, er => {
  2105. if (er)
  2106. this.emit('error', er);
  2107. else
  2108. this.emit('close');
  2109. });
  2110. this.fd = null;
  2111. };
  2112. FsWriteStream.prototype._destroy = FsReadStream.prototype._destroy;
  2113. // There is no shutdown() for files.
  2114. FsWriteStream.prototype.destroySoon = FsWriteStream.prototype.end;
  2115. // ---------------------------------------- FSWatcher
  2116. class FSWatcher extends events_1.EventEmitter {
  2117. constructor(vol) {
  2118. super();
  2119. this._filename = '';
  2120. this._filenameEncoded = '';
  2121. // _persistent: boolean = true;
  2122. this._recursive = false;
  2123. this._encoding = encoding_1.ENCODING_UTF8;
  2124. // inode -> removers
  2125. this._listenerRemovers = new Map();
  2126. this._onParentChild = (link) => {
  2127. if (link.getName() === this._getName()) {
  2128. this._emit('rename');
  2129. }
  2130. };
  2131. this._emit = (type) => {
  2132. this.emit('change', type, this._filenameEncoded);
  2133. };
  2134. this._persist = () => {
  2135. this._timer = setTimeout(this._persist, 1e6);
  2136. };
  2137. this._vol = vol;
  2138. // TODO: Emit "error" messages when watching.
  2139. // this._handle.onchange = function(status, eventType, filename) {
  2140. // if (status < 0) {
  2141. // self._handle.close();
  2142. // const error = !filename ?
  2143. // errnoException(status, 'Error watching file for changes:') :
  2144. // errnoException(status, `Error watching file ${filename} for changes:`);
  2145. // error.filename = filename;
  2146. // self.emit('error', error);
  2147. // } else {
  2148. // self.emit('change', eventType, filename);
  2149. // }
  2150. // };
  2151. }
  2152. _getName() {
  2153. return this._steps[this._steps.length - 1];
  2154. }
  2155. start(path, persistent = true, recursive = false, encoding = encoding_1.ENCODING_UTF8) {
  2156. this._filename = pathToFilename(path);
  2157. this._steps = filenameToSteps(this._filename);
  2158. this._filenameEncoded = (0, encoding_1.strToEncoding)(this._filename);
  2159. // this._persistent = persistent;
  2160. this._recursive = recursive;
  2161. this._encoding = encoding;
  2162. try {
  2163. this._link = this._vol.getLinkOrThrow(this._filename, 'FSWatcher');
  2164. }
  2165. catch (err) {
  2166. const error = new Error(`watch ${this._filename} ${err.code}`);
  2167. error.code = err.code;
  2168. error.errno = err.code;
  2169. throw error;
  2170. }
  2171. const watchLinkNodeChanged = (link) => {
  2172. var _a;
  2173. const filepath = link.getPath();
  2174. const node = link.getNode();
  2175. const onNodeChange = () => {
  2176. let filename = relative(this._filename, filepath);
  2177. if (!filename) {
  2178. filename = this._getName();
  2179. }
  2180. return this.emit('change', 'change', filename);
  2181. };
  2182. node.on('change', onNodeChange);
  2183. const removers = (_a = this._listenerRemovers.get(node.ino)) !== null && _a !== void 0 ? _a : [];
  2184. removers.push(() => node.removeListener('change', onNodeChange));
  2185. this._listenerRemovers.set(node.ino, removers);
  2186. };
  2187. const watchLinkChildrenChanged = (link) => {
  2188. var _a;
  2189. const node = link.getNode();
  2190. // when a new link added
  2191. const onLinkChildAdd = (l) => {
  2192. this.emit('change', 'rename', relative(this._filename, l.getPath()));
  2193. setTimeout(() => {
  2194. // 1. watch changes of the new link-node
  2195. watchLinkNodeChanged(l);
  2196. // 2. watch changes of the new link-node's children
  2197. watchLinkChildrenChanged(l);
  2198. });
  2199. };
  2200. // when a new link deleted
  2201. const onLinkChildDelete = (l) => {
  2202. // remove the listeners of the children nodes
  2203. const removeLinkNodeListeners = (curLink) => {
  2204. const ino = curLink.getNode().ino;
  2205. const removers = this._listenerRemovers.get(ino);
  2206. if (removers) {
  2207. removers.forEach(r => r());
  2208. this._listenerRemovers.delete(ino);
  2209. }
  2210. Object.values(curLink.children).forEach(childLink => {
  2211. if (childLink) {
  2212. removeLinkNodeListeners(childLink);
  2213. }
  2214. });
  2215. };
  2216. removeLinkNodeListeners(l);
  2217. this.emit('change', 'rename', relative(this._filename, l.getPath()));
  2218. };
  2219. // children nodes changed
  2220. Object.entries(link.children).forEach(([name, childLink]) => {
  2221. if (childLink && name !== '.' && name !== '..') {
  2222. watchLinkNodeChanged(childLink);
  2223. }
  2224. });
  2225. // link children add/remove
  2226. link.on('child:add', onLinkChildAdd);
  2227. link.on('child:delete', onLinkChildDelete);
  2228. const removers = (_a = this._listenerRemovers.get(node.ino)) !== null && _a !== void 0 ? _a : [];
  2229. removers.push(() => {
  2230. link.removeListener('child:add', onLinkChildAdd);
  2231. link.removeListener('child:delete', onLinkChildDelete);
  2232. });
  2233. if (recursive) {
  2234. Object.entries(link.children).forEach(([name, childLink]) => {
  2235. if (childLink && name !== '.' && name !== '..') {
  2236. watchLinkChildrenChanged(childLink);
  2237. }
  2238. });
  2239. }
  2240. };
  2241. watchLinkNodeChanged(this._link);
  2242. watchLinkChildrenChanged(this._link);
  2243. const parent = this._link.parent;
  2244. if (parent) {
  2245. // parent.on('child:add', this._onParentChild);
  2246. parent.setMaxListeners(parent.getMaxListeners() + 1);
  2247. parent.on('child:delete', this._onParentChild);
  2248. }
  2249. if (persistent)
  2250. this._persist();
  2251. }
  2252. close() {
  2253. clearTimeout(this._timer);
  2254. this._listenerRemovers.forEach(removers => {
  2255. removers.forEach(r => r());
  2256. });
  2257. this._listenerRemovers.clear();
  2258. const parent = this._link.parent;
  2259. if (parent) {
  2260. // parent.removeListener('child:add', this._onParentChild);
  2261. parent.removeListener('child:delete', this._onParentChild);
  2262. }
  2263. }
  2264. }
  2265. exports.FSWatcher = FSWatcher;