cde1970db6b88a947091bbb06dd815e4643228ea4a4065634c9371adf97947597c3e4f3b920e32a1e95d075849fa53ada15b711d4ff917b8a63106c3186c54 185 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437
  1. /**
  2. * The `node:fs` module enables interacting with the file system in a
  3. * way modeled on standard POSIX functions.
  4. *
  5. * To use the promise-based APIs:
  6. *
  7. * ```js
  8. * import * as fs from 'node:fs/promises';
  9. * ```
  10. *
  11. * To use the callback and sync APIs:
  12. *
  13. * ```js
  14. * import * as fs from 'node:fs';
  15. * ```
  16. *
  17. * All file system operations have synchronous, callback, and promise-based
  18. * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).
  19. * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/fs.js)
  20. */
  21. declare module "fs" {
  22. import * as stream from "node:stream";
  23. import { Abortable, EventEmitter } from "node:events";
  24. import { URL } from "node:url";
  25. import * as promises from "node:fs/promises";
  26. export { promises };
  27. /**
  28. * Valid types for path values in "fs".
  29. */
  30. export type PathLike = string | Buffer | URL;
  31. export type PathOrFileDescriptor = PathLike | number;
  32. export type TimeLike = string | number | Date;
  33. export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void;
  34. export type BufferEncodingOption =
  35. | "buffer"
  36. | {
  37. encoding: "buffer";
  38. };
  39. export interface ObjectEncodingOptions {
  40. encoding?: BufferEncoding | null | undefined;
  41. }
  42. export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null;
  43. export type OpenMode = number | string;
  44. export type Mode = number | string;
  45. export interface StatsBase<T> {
  46. isFile(): boolean;
  47. isDirectory(): boolean;
  48. isBlockDevice(): boolean;
  49. isCharacterDevice(): boolean;
  50. isSymbolicLink(): boolean;
  51. isFIFO(): boolean;
  52. isSocket(): boolean;
  53. dev: T;
  54. ino: T;
  55. mode: T;
  56. nlink: T;
  57. uid: T;
  58. gid: T;
  59. rdev: T;
  60. size: T;
  61. blksize: T;
  62. blocks: T;
  63. atimeMs: T;
  64. mtimeMs: T;
  65. ctimeMs: T;
  66. birthtimeMs: T;
  67. atime: Date;
  68. mtime: Date;
  69. ctime: Date;
  70. birthtime: Date;
  71. }
  72. export interface Stats extends StatsBase<number> {}
  73. /**
  74. * A `fs.Stats` object provides information about a file.
  75. *
  76. * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and
  77. * their synchronous counterparts are of this type.
  78. * If `bigint` in the `options` passed to those methods is true, the numeric values
  79. * will be `bigint` instead of `number`, and the object will contain additional
  80. * nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword.
  81. *
  82. * ```console
  83. * Stats {
  84. * dev: 2114,
  85. * ino: 48064969,
  86. * mode: 33188,
  87. * nlink: 1,
  88. * uid: 85,
  89. * gid: 100,
  90. * rdev: 0,
  91. * size: 527,
  92. * blksize: 4096,
  93. * blocks: 8,
  94. * atimeMs: 1318289051000.1,
  95. * mtimeMs: 1318289051000.1,
  96. * ctimeMs: 1318289051000.1,
  97. * birthtimeMs: 1318289051000.1,
  98. * atime: Mon, 10 Oct 2011 23:24:11 GMT,
  99. * mtime: Mon, 10 Oct 2011 23:24:11 GMT,
  100. * ctime: Mon, 10 Oct 2011 23:24:11 GMT,
  101. * birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
  102. * ```
  103. *
  104. * `bigint` version:
  105. *
  106. * ```console
  107. * BigIntStats {
  108. * dev: 2114n,
  109. * ino: 48064969n,
  110. * mode: 33188n,
  111. * nlink: 1n,
  112. * uid: 85n,
  113. * gid: 100n,
  114. * rdev: 0n,
  115. * size: 527n,
  116. * blksize: 4096n,
  117. * blocks: 8n,
  118. * atimeMs: 1318289051000n,
  119. * mtimeMs: 1318289051000n,
  120. * ctimeMs: 1318289051000n,
  121. * birthtimeMs: 1318289051000n,
  122. * atimeNs: 1318289051000000000n,
  123. * mtimeNs: 1318289051000000000n,
  124. * ctimeNs: 1318289051000000000n,
  125. * birthtimeNs: 1318289051000000000n,
  126. * atime: Mon, 10 Oct 2011 23:24:11 GMT,
  127. * mtime: Mon, 10 Oct 2011 23:24:11 GMT,
  128. * ctime: Mon, 10 Oct 2011 23:24:11 GMT,
  129. * birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
  130. * ```
  131. * @since v0.1.21
  132. */
  133. export class Stats {
  134. private constructor();
  135. }
  136. export interface StatsFsBase<T> {
  137. /** Type of file system. */
  138. type: T;
  139. /** Optimal transfer block size. */
  140. bsize: T;
  141. /** Total data blocks in file system. */
  142. blocks: T;
  143. /** Free blocks in file system. */
  144. bfree: T;
  145. /** Available blocks for unprivileged users */
  146. bavail: T;
  147. /** Total file nodes in file system. */
  148. files: T;
  149. /** Free file nodes in file system. */
  150. ffree: T;
  151. }
  152. export interface StatsFs extends StatsFsBase<number> {}
  153. /**
  154. * Provides information about a mounted file system.
  155. *
  156. * Objects returned from {@link statfs} and its synchronous counterpart are of
  157. * this type. If `bigint` in the `options` passed to those methods is `true`, the
  158. * numeric values will be `bigint` instead of `number`.
  159. *
  160. * ```console
  161. * StatFs {
  162. * type: 1397114950,
  163. * bsize: 4096,
  164. * blocks: 121938943,
  165. * bfree: 61058895,
  166. * bavail: 61058895,
  167. * files: 999,
  168. * ffree: 1000000
  169. * }
  170. * ```
  171. *
  172. * `bigint` version:
  173. *
  174. * ```console
  175. * StatFs {
  176. * type: 1397114950n,
  177. * bsize: 4096n,
  178. * blocks: 121938943n,
  179. * bfree: 61058895n,
  180. * bavail: 61058895n,
  181. * files: 999n,
  182. * ffree: 1000000n
  183. * }
  184. * ```
  185. * @since v19.6.0, v18.15.0
  186. */
  187. export class StatsFs {}
  188. export interface BigIntStatsFs extends StatsFsBase<bigint> {}
  189. export interface StatFsOptions {
  190. bigint?: boolean | undefined;
  191. }
  192. /**
  193. * A representation of a directory entry, which can be a file or a subdirectory
  194. * within the directory, as returned by reading from an `fs.Dir`. The
  195. * directory entry is a combination of the file name and file type pairs.
  196. *
  197. * Additionally, when {@link readdir} or {@link readdirSync} is called with
  198. * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s.
  199. * @since v10.10.0
  200. */
  201. export class Dirent<Name extends string | Buffer = string> {
  202. /**
  203. * Returns `true` if the `fs.Dirent` object describes a regular file.
  204. * @since v10.10.0
  205. */
  206. isFile(): boolean;
  207. /**
  208. * Returns `true` if the `fs.Dirent` object describes a file system
  209. * directory.
  210. * @since v10.10.0
  211. */
  212. isDirectory(): boolean;
  213. /**
  214. * Returns `true` if the `fs.Dirent` object describes a block device.
  215. * @since v10.10.0
  216. */
  217. isBlockDevice(): boolean;
  218. /**
  219. * Returns `true` if the `fs.Dirent` object describes a character device.
  220. * @since v10.10.0
  221. */
  222. isCharacterDevice(): boolean;
  223. /**
  224. * Returns `true` if the `fs.Dirent` object describes a symbolic link.
  225. * @since v10.10.0
  226. */
  227. isSymbolicLink(): boolean;
  228. /**
  229. * Returns `true` if the `fs.Dirent` object describes a first-in-first-out
  230. * (FIFO) pipe.
  231. * @since v10.10.0
  232. */
  233. isFIFO(): boolean;
  234. /**
  235. * Returns `true` if the `fs.Dirent` object describes a socket.
  236. * @since v10.10.0
  237. */
  238. isSocket(): boolean;
  239. /**
  240. * The file name that this `fs.Dirent` object refers to. The type of this
  241. * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}.
  242. * @since v10.10.0
  243. */
  244. name: Name;
  245. /**
  246. * The base path that this `fs.Dirent` object refers to.
  247. * @since v20.12.0
  248. */
  249. parentPath: string;
  250. /**
  251. * Alias for `dirent.parentPath`.
  252. * @since v20.1.0
  253. * @deprecated Since v20.12.0
  254. */
  255. path: string;
  256. }
  257. /**
  258. * A class representing a directory stream.
  259. *
  260. * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`.
  261. *
  262. * ```js
  263. * import { opendir } from 'node:fs/promises';
  264. *
  265. * try {
  266. * const dir = await opendir('./');
  267. * for await (const dirent of dir)
  268. * console.log(dirent.name);
  269. * } catch (err) {
  270. * console.error(err);
  271. * }
  272. * ```
  273. *
  274. * When using the async iterator, the `fs.Dir` object will be automatically
  275. * closed after the iterator exits.
  276. * @since v12.12.0
  277. */
  278. export class Dir implements AsyncIterable<Dirent> {
  279. /**
  280. * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`.
  281. * @since v12.12.0
  282. */
  283. readonly path: string;
  284. /**
  285. * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read.
  286. */
  287. [Symbol.asyncIterator](): NodeJS.AsyncIterator<Dirent>;
  288. /**
  289. * Asynchronously close the directory's underlying resource handle.
  290. * Subsequent reads will result in errors.
  291. *
  292. * A promise is returned that will be fulfilled after the resource has been
  293. * closed.
  294. * @since v12.12.0
  295. */
  296. close(): Promise<void>;
  297. close(cb: NoParamCallback): void;
  298. /**
  299. * Synchronously close the directory's underlying resource handle.
  300. * Subsequent reads will result in errors.
  301. * @since v12.12.0
  302. */
  303. closeSync(): void;
  304. /**
  305. * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`.
  306. *
  307. * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null` if there are no more directory entries to read.
  308. *
  309. * Directory entries returned by this function are in no particular order as
  310. * provided by the operating system's underlying directory mechanisms.
  311. * Entries added or removed while iterating over the directory might not be
  312. * included in the iteration results.
  313. * @since v12.12.0
  314. * @return containing {fs.Dirent|null}
  315. */
  316. read(): Promise<Dirent | null>;
  317. read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void;
  318. /**
  319. * Synchronously read the next directory entry as an `fs.Dirent`. See the
  320. * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail.
  321. *
  322. * If there are no more directory entries to read, `null` will be returned.
  323. *
  324. * Directory entries returned by this function are in no particular order as
  325. * provided by the operating system's underlying directory mechanisms.
  326. * Entries added or removed while iterating over the directory might not be
  327. * included in the iteration results.
  328. * @since v12.12.0
  329. */
  330. readSync(): Dirent | null;
  331. }
  332. /**
  333. * Class: fs.StatWatcher
  334. * @since v14.3.0, v12.20.0
  335. * Extends `EventEmitter`
  336. * A successful call to {@link watchFile} method will return a new fs.StatWatcher object.
  337. */
  338. export interface StatWatcher extends EventEmitter {
  339. /**
  340. * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have
  341. * no effect.
  342. *
  343. * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally
  344. * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been
  345. * called previously.
  346. * @since v14.3.0, v12.20.0
  347. */
  348. ref(): this;
  349. /**
  350. * When called, the active `fs.StatWatcher` object will not require the Node.js
  351. * event loop to remain active. If there is no other activity keeping the
  352. * event loop running, the process may exit before the `fs.StatWatcher` object's
  353. * callback is invoked. Calling `watcher.unref()` multiple times will have
  354. * no effect.
  355. * @since v14.3.0, v12.20.0
  356. */
  357. unref(): this;
  358. }
  359. export interface FSWatcher extends EventEmitter {
  360. /**
  361. * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable.
  362. * @since v0.5.8
  363. */
  364. close(): void;
  365. /**
  366. * When called, requests that the Node.js event loop _not_ exit so long as the `fs.FSWatcher` is active. Calling `watcher.ref()` multiple times will have
  367. * no effect.
  368. *
  369. * By default, all `fs.FSWatcher` objects are "ref'ed", making it normally
  370. * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been
  371. * called previously.
  372. * @since v14.3.0, v12.20.0
  373. */
  374. ref(): this;
  375. /**
  376. * When called, the active `fs.FSWatcher` object will not require the Node.js
  377. * event loop to remain active. If there is no other activity keeping the
  378. * event loop running, the process may exit before the `fs.FSWatcher` object's
  379. * callback is invoked. Calling `watcher.unref()` multiple times will have
  380. * no effect.
  381. * @since v14.3.0, v12.20.0
  382. */
  383. unref(): this;
  384. /**
  385. * events.EventEmitter
  386. * 1. change
  387. * 2. close
  388. * 3. error
  389. */
  390. addListener(event: string, listener: (...args: any[]) => void): this;
  391. addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this;
  392. addListener(event: "close", listener: () => void): this;
  393. addListener(event: "error", listener: (error: Error) => void): this;
  394. on(event: string, listener: (...args: any[]) => void): this;
  395. on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this;
  396. on(event: "close", listener: () => void): this;
  397. on(event: "error", listener: (error: Error) => void): this;
  398. once(event: string, listener: (...args: any[]) => void): this;
  399. once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this;
  400. once(event: "close", listener: () => void): this;
  401. once(event: "error", listener: (error: Error) => void): this;
  402. prependListener(event: string, listener: (...args: any[]) => void): this;
  403. prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this;
  404. prependListener(event: "close", listener: () => void): this;
  405. prependListener(event: "error", listener: (error: Error) => void): this;
  406. prependOnceListener(event: string, listener: (...args: any[]) => void): this;
  407. prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this;
  408. prependOnceListener(event: "close", listener: () => void): this;
  409. prependOnceListener(event: "error", listener: (error: Error) => void): this;
  410. }
  411. /**
  412. * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function.
  413. * @since v0.1.93
  414. */
  415. export class ReadStream extends stream.Readable {
  416. close(callback?: (err?: NodeJS.ErrnoException | null) => void): void;
  417. /**
  418. * The number of bytes that have been read so far.
  419. * @since v6.4.0
  420. */
  421. bytesRead: number;
  422. /**
  423. * The path to the file the stream is reading from as specified in the first
  424. * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a
  425. * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`.
  426. * @since v0.1.93
  427. */
  428. path: string | Buffer;
  429. /**
  430. * This property is `true` if the underlying file has not been opened yet,
  431. * i.e. before the `'ready'` event is emitted.
  432. * @since v11.2.0, v10.16.0
  433. */
  434. pending: boolean;
  435. /**
  436. * events.EventEmitter
  437. * 1. open
  438. * 2. close
  439. * 3. ready
  440. */
  441. addListener<K extends keyof ReadStreamEvents>(event: K, listener: ReadStreamEvents[K]): this;
  442. on<K extends keyof ReadStreamEvents>(event: K, listener: ReadStreamEvents[K]): this;
  443. once<K extends keyof ReadStreamEvents>(event: K, listener: ReadStreamEvents[K]): this;
  444. prependListener<K extends keyof ReadStreamEvents>(event: K, listener: ReadStreamEvents[K]): this;
  445. prependOnceListener<K extends keyof ReadStreamEvents>(event: K, listener: ReadStreamEvents[K]): this;
  446. }
  447. /**
  448. * The Keys are events of the ReadStream and the values are the functions that are called when the event is emitted.
  449. */
  450. type ReadStreamEvents = {
  451. close: () => void;
  452. data: (chunk: Buffer | string) => void;
  453. end: () => void;
  454. error: (err: Error) => void;
  455. open: (fd: number) => void;
  456. pause: () => void;
  457. readable: () => void;
  458. ready: () => void;
  459. resume: () => void;
  460. } & CustomEvents;
  461. /**
  462. * string & {} allows to allow any kind of strings for the event
  463. * but still allows to have auto completion for the normal events.
  464. */
  465. type CustomEvents = { [Key in string & {} | symbol]: (...args: any[]) => void };
  466. /**
  467. * The Keys are events of the WriteStream and the values are the functions that are called when the event is emitted.
  468. */
  469. type WriteStreamEvents = {
  470. close: () => void;
  471. drain: () => void;
  472. error: (err: Error) => void;
  473. finish: () => void;
  474. open: (fd: number) => void;
  475. pipe: (src: stream.Readable) => void;
  476. ready: () => void;
  477. unpipe: (src: stream.Readable) => void;
  478. } & CustomEvents;
  479. /**
  480. * * Extends `stream.Writable`
  481. *
  482. * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function.
  483. * @since v0.1.93
  484. */
  485. export class WriteStream extends stream.Writable {
  486. /**
  487. * Closes `writeStream`. Optionally accepts a
  488. * callback that will be executed once the `writeStream`is closed.
  489. * @since v0.9.4
  490. */
  491. close(callback?: (err?: NodeJS.ErrnoException | null) => void): void;
  492. /**
  493. * The number of bytes written so far. Does not include data that is still queued
  494. * for writing.
  495. * @since v0.4.7
  496. */
  497. bytesWritten: number;
  498. /**
  499. * The path to the file the stream is writing to as specified in the first
  500. * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a
  501. * `Buffer`.
  502. * @since v0.1.93
  503. */
  504. path: string | Buffer;
  505. /**
  506. * This property is `true` if the underlying file has not been opened yet,
  507. * i.e. before the `'ready'` event is emitted.
  508. * @since v11.2.0
  509. */
  510. pending: boolean;
  511. /**
  512. * events.EventEmitter
  513. * 1. open
  514. * 2. close
  515. * 3. ready
  516. */
  517. addListener<K extends keyof WriteStreamEvents>(event: K, listener: WriteStreamEvents[K]): this;
  518. on<K extends keyof WriteStreamEvents>(event: K, listener: WriteStreamEvents[K]): this;
  519. once<K extends keyof WriteStreamEvents>(event: K, listener: WriteStreamEvents[K]): this;
  520. prependListener<K extends keyof WriteStreamEvents>(event: K, listener: WriteStreamEvents[K]): this;
  521. prependOnceListener<K extends keyof WriteStreamEvents>(event: K, listener: WriteStreamEvents[K]): this;
  522. }
  523. /**
  524. * Asynchronously rename file at `oldPath` to the pathname provided
  525. * as `newPath`. In the case that `newPath` already exists, it will
  526. * be overwritten. If there is a directory at `newPath`, an error will
  527. * be raised instead. No arguments other than a possible exception are
  528. * given to the completion callback.
  529. *
  530. * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html).
  531. *
  532. * ```js
  533. * import { rename } from 'node:fs';
  534. *
  535. * rename('oldFile.txt', 'newFile.txt', (err) => {
  536. * if (err) throw err;
  537. * console.log('Rename complete!');
  538. * });
  539. * ```
  540. * @since v0.0.2
  541. */
  542. export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void;
  543. export namespace rename {
  544. /**
  545. * Asynchronous rename(2) - Change the name or location of a file or directory.
  546. * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol.
  547. * URL support is _experimental_.
  548. * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol.
  549. * URL support is _experimental_.
  550. */
  551. function __promisify__(oldPath: PathLike, newPath: PathLike): Promise<void>;
  552. }
  553. /**
  554. * Renames the file from `oldPath` to `newPath`. Returns `undefined`.
  555. *
  556. * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details.
  557. * @since v0.1.21
  558. */
  559. export function renameSync(oldPath: PathLike, newPath: PathLike): void;
  560. /**
  561. * Truncates the file. No arguments other than a possible exception are
  562. * given to the completion callback. A file descriptor can also be passed as the
  563. * first argument. In this case, `fs.ftruncate()` is called.
  564. *
  565. * ```js
  566. * import { truncate } from 'node:fs';
  567. * // Assuming that 'path/file.txt' is a regular file.
  568. * truncate('path/file.txt', (err) => {
  569. * if (err) throw err;
  570. * console.log('path/file.txt was truncated');
  571. * });
  572. * ```
  573. *
  574. * Passing a file descriptor is deprecated and may result in an error being thrown
  575. * in the future.
  576. *
  577. * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details.
  578. * @since v0.8.6
  579. * @param [len=0]
  580. */
  581. export function truncate(path: PathLike, len: number | undefined, callback: NoParamCallback): void;
  582. /**
  583. * Asynchronous truncate(2) - Truncate a file to a specified length.
  584. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  585. */
  586. export function truncate(path: PathLike, callback: NoParamCallback): void;
  587. export namespace truncate {
  588. /**
  589. * Asynchronous truncate(2) - Truncate a file to a specified length.
  590. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  591. * @param len If not specified, defaults to `0`.
  592. */
  593. function __promisify__(path: PathLike, len?: number): Promise<void>;
  594. }
  595. /**
  596. * Truncates the file. Returns `undefined`. A file descriptor can also be
  597. * passed as the first argument. In this case, `fs.ftruncateSync()` is called.
  598. *
  599. * Passing a file descriptor is deprecated and may result in an error being thrown
  600. * in the future.
  601. * @since v0.8.6
  602. * @param [len=0]
  603. */
  604. export function truncateSync(path: PathLike, len?: number): void;
  605. /**
  606. * Truncates the file descriptor. No arguments other than a possible exception are
  607. * given to the completion callback.
  608. *
  609. * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail.
  610. *
  611. * If the file referred to by the file descriptor was larger than `len` bytes, only
  612. * the first `len` bytes will be retained in the file.
  613. *
  614. * For example, the following program retains only the first four bytes of the
  615. * file:
  616. *
  617. * ```js
  618. * import { open, close, ftruncate } from 'node:fs';
  619. *
  620. * function closeFd(fd) {
  621. * close(fd, (err) => {
  622. * if (err) throw err;
  623. * });
  624. * }
  625. *
  626. * open('temp.txt', 'r+', (err, fd) => {
  627. * if (err) throw err;
  628. *
  629. * try {
  630. * ftruncate(fd, 4, (err) => {
  631. * closeFd(fd);
  632. * if (err) throw err;
  633. * });
  634. * } catch (err) {
  635. * closeFd(fd);
  636. * if (err) throw err;
  637. * }
  638. * });
  639. * ```
  640. *
  641. * If the file previously was shorter than `len` bytes, it is extended, and the
  642. * extended part is filled with null bytes (`'\0'`):
  643. *
  644. * If `len` is negative then `0` will be used.
  645. * @since v0.8.6
  646. * @param [len=0]
  647. */
  648. export function ftruncate(fd: number, len: number | undefined, callback: NoParamCallback): void;
  649. /**
  650. * Asynchronous ftruncate(2) - Truncate a file to a specified length.
  651. * @param fd A file descriptor.
  652. */
  653. export function ftruncate(fd: number, callback: NoParamCallback): void;
  654. export namespace ftruncate {
  655. /**
  656. * Asynchronous ftruncate(2) - Truncate a file to a specified length.
  657. * @param fd A file descriptor.
  658. * @param len If not specified, defaults to `0`.
  659. */
  660. function __promisify__(fd: number, len?: number): Promise<void>;
  661. }
  662. /**
  663. * Truncates the file descriptor. Returns `undefined`.
  664. *
  665. * For detailed information, see the documentation of the asynchronous version of
  666. * this API: {@link ftruncate}.
  667. * @since v0.8.6
  668. * @param [len=0]
  669. */
  670. export function ftruncateSync(fd: number, len?: number): void;
  671. /**
  672. * Asynchronously changes owner and group of a file. No arguments other than a
  673. * possible exception are given to the completion callback.
  674. *
  675. * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail.
  676. * @since v0.1.97
  677. */
  678. export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void;
  679. export namespace chown {
  680. /**
  681. * Asynchronous chown(2) - Change ownership of a file.
  682. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  683. */
  684. function __promisify__(path: PathLike, uid: number, gid: number): Promise<void>;
  685. }
  686. /**
  687. * Synchronously changes owner and group of a file. Returns `undefined`.
  688. * This is the synchronous version of {@link chown}.
  689. *
  690. * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail.
  691. * @since v0.1.97
  692. */
  693. export function chownSync(path: PathLike, uid: number, gid: number): void;
  694. /**
  695. * Sets the owner of the file. No arguments other than a possible exception are
  696. * given to the completion callback.
  697. *
  698. * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail.
  699. * @since v0.4.7
  700. */
  701. export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void;
  702. export namespace fchown {
  703. /**
  704. * Asynchronous fchown(2) - Change ownership of a file.
  705. * @param fd A file descriptor.
  706. */
  707. function __promisify__(fd: number, uid: number, gid: number): Promise<void>;
  708. }
  709. /**
  710. * Sets the owner of the file. Returns `undefined`.
  711. *
  712. * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail.
  713. * @since v0.4.7
  714. * @param uid The file's new owner's user id.
  715. * @param gid The file's new group's group id.
  716. */
  717. export function fchownSync(fd: number, uid: number, gid: number): void;
  718. /**
  719. * Set the owner of the symbolic link. No arguments other than a possible
  720. * exception are given to the completion callback.
  721. *
  722. * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail.
  723. */
  724. export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void;
  725. export namespace lchown {
  726. /**
  727. * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links.
  728. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  729. */
  730. function __promisify__(path: PathLike, uid: number, gid: number): Promise<void>;
  731. }
  732. /**
  733. * Set the owner for the path. Returns `undefined`.
  734. *
  735. * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details.
  736. * @param uid The file's new owner's user id.
  737. * @param gid The file's new group's group id.
  738. */
  739. export function lchownSync(path: PathLike, uid: number, gid: number): void;
  740. /**
  741. * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic
  742. * link, then the link is not dereferenced: instead, the timestamps of the
  743. * symbolic link itself are changed.
  744. *
  745. * No arguments other than a possible exception are given to the completion
  746. * callback.
  747. * @since v14.5.0, v12.19.0
  748. */
  749. export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void;
  750. export namespace lutimes {
  751. /**
  752. * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`,
  753. * with the difference that if the path refers to a symbolic link, then the link is not
  754. * dereferenced: instead, the timestamps of the symbolic link itself are changed.
  755. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  756. * @param atime The last access time. If a string is provided, it will be coerced to number.
  757. * @param mtime The last modified time. If a string is provided, it will be coerced to number.
  758. */
  759. function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise<void>;
  760. }
  761. /**
  762. * Change the file system timestamps of the symbolic link referenced by `path`.
  763. * Returns `undefined`, or throws an exception when parameters are incorrect or
  764. * the operation fails. This is the synchronous version of {@link lutimes}.
  765. * @since v14.5.0, v12.19.0
  766. */
  767. export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void;
  768. /**
  769. * Asynchronously changes the permissions of a file. No arguments other than a
  770. * possible exception are given to the completion callback.
  771. *
  772. * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail.
  773. *
  774. * ```js
  775. * import { chmod } from 'node:fs';
  776. *
  777. * chmod('my_file.txt', 0o775, (err) => {
  778. * if (err) throw err;
  779. * console.log('The permissions for file "my_file.txt" have been changed!');
  780. * });
  781. * ```
  782. * @since v0.1.30
  783. */
  784. export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void;
  785. export namespace chmod {
  786. /**
  787. * Asynchronous chmod(2) - Change permissions of a file.
  788. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  789. * @param mode A file mode. If a string is passed, it is parsed as an octal integer.
  790. */
  791. function __promisify__(path: PathLike, mode: Mode): Promise<void>;
  792. }
  793. /**
  794. * For detailed information, see the documentation of the asynchronous version of
  795. * this API: {@link chmod}.
  796. *
  797. * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail.
  798. * @since v0.6.7
  799. */
  800. export function chmodSync(path: PathLike, mode: Mode): void;
  801. /**
  802. * Sets the permissions on the file. No arguments other than a possible exception
  803. * are given to the completion callback.
  804. *
  805. * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail.
  806. * @since v0.4.7
  807. */
  808. export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void;
  809. export namespace fchmod {
  810. /**
  811. * Asynchronous fchmod(2) - Change permissions of a file.
  812. * @param fd A file descriptor.
  813. * @param mode A file mode. If a string is passed, it is parsed as an octal integer.
  814. */
  815. function __promisify__(fd: number, mode: Mode): Promise<void>;
  816. }
  817. /**
  818. * Sets the permissions on the file. Returns `undefined`.
  819. *
  820. * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail.
  821. * @since v0.4.7
  822. */
  823. export function fchmodSync(fd: number, mode: Mode): void;
  824. /**
  825. * Changes the permissions on a symbolic link. No arguments other than a possible
  826. * exception are given to the completion callback.
  827. *
  828. * This method is only implemented on macOS.
  829. *
  830. * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail.
  831. * @deprecated Since v0.4.7
  832. */
  833. export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void;
  834. /** @deprecated */
  835. export namespace lchmod {
  836. /**
  837. * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links.
  838. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  839. * @param mode A file mode. If a string is passed, it is parsed as an octal integer.
  840. */
  841. function __promisify__(path: PathLike, mode: Mode): Promise<void>;
  842. }
  843. /**
  844. * Changes the permissions on a symbolic link. Returns `undefined`.
  845. *
  846. * This method is only implemented on macOS.
  847. *
  848. * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail.
  849. * @deprecated Since v0.4.7
  850. */
  851. export function lchmodSync(path: PathLike, mode: Mode): void;
  852. /**
  853. * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object.
  854. *
  855. * In case of an error, the `err.code` will be one of `Common System Errors`.
  856. *
  857. * {@link stat} follows symbolic links. Use {@link lstat} to look at the
  858. * links themselves.
  859. *
  860. * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended.
  861. * Instead, user code should open/read/write the file directly and handle the
  862. * error raised if the file is not available.
  863. *
  864. * To check if a file exists without manipulating it afterwards, {@link access} is recommended.
  865. *
  866. * For example, given the following directory structure:
  867. *
  868. * ```text
  869. * - txtDir
  870. * -- file.txt
  871. * - app.js
  872. * ```
  873. *
  874. * The next program will check for the stats of the given paths:
  875. *
  876. * ```js
  877. * import { stat } from 'node:fs';
  878. *
  879. * const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
  880. *
  881. * for (let i = 0; i < pathsToCheck.length; i++) {
  882. * stat(pathsToCheck[i], (err, stats) => {
  883. * console.log(stats.isDirectory());
  884. * console.log(stats);
  885. * });
  886. * }
  887. * ```
  888. *
  889. * The resulting output will resemble:
  890. *
  891. * ```console
  892. * true
  893. * Stats {
  894. * dev: 16777220,
  895. * mode: 16877,
  896. * nlink: 3,
  897. * uid: 501,
  898. * gid: 20,
  899. * rdev: 0,
  900. * blksize: 4096,
  901. * ino: 14214262,
  902. * size: 96,
  903. * blocks: 0,
  904. * atimeMs: 1561174653071.963,
  905. * mtimeMs: 1561174614583.3518,
  906. * ctimeMs: 1561174626623.5366,
  907. * birthtimeMs: 1561174126937.2893,
  908. * atime: 2019-06-22T03:37:33.072Z,
  909. * mtime: 2019-06-22T03:36:54.583Z,
  910. * ctime: 2019-06-22T03:37:06.624Z,
  911. * birthtime: 2019-06-22T03:28:46.937Z
  912. * }
  913. * false
  914. * Stats {
  915. * dev: 16777220,
  916. * mode: 33188,
  917. * nlink: 1,
  918. * uid: 501,
  919. * gid: 20,
  920. * rdev: 0,
  921. * blksize: 4096,
  922. * ino: 14214074,
  923. * size: 8,
  924. * blocks: 8,
  925. * atimeMs: 1561174616618.8555,
  926. * mtimeMs: 1561174614584,
  927. * ctimeMs: 1561174614583.8145,
  928. * birthtimeMs: 1561174007710.7478,
  929. * atime: 2019-06-22T03:36:56.619Z,
  930. * mtime: 2019-06-22T03:36:54.584Z,
  931. * ctime: 2019-06-22T03:36:54.584Z,
  932. * birthtime: 2019-06-22T03:26:47.711Z
  933. * }
  934. * ```
  935. * @since v0.0.2
  936. */
  937. export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void;
  938. export function stat(
  939. path: PathLike,
  940. options:
  941. | (StatOptions & {
  942. bigint?: false | undefined;
  943. })
  944. | undefined,
  945. callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void,
  946. ): void;
  947. export function stat(
  948. path: PathLike,
  949. options: StatOptions & {
  950. bigint: true;
  951. },
  952. callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void,
  953. ): void;
  954. export function stat(
  955. path: PathLike,
  956. options: StatOptions | undefined,
  957. callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void,
  958. ): void;
  959. export namespace stat {
  960. /**
  961. * Asynchronous stat(2) - Get file status.
  962. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  963. */
  964. function __promisify__(
  965. path: PathLike,
  966. options?: StatOptions & {
  967. bigint?: false | undefined;
  968. },
  969. ): Promise<Stats>;
  970. function __promisify__(
  971. path: PathLike,
  972. options: StatOptions & {
  973. bigint: true;
  974. },
  975. ): Promise<BigIntStats>;
  976. function __promisify__(path: PathLike, options?: StatOptions): Promise<Stats | BigIntStats>;
  977. }
  978. export interface StatSyncFn extends Function {
  979. (path: PathLike, options?: undefined): Stats;
  980. (
  981. path: PathLike,
  982. options?: StatSyncOptions & {
  983. bigint?: false | undefined;
  984. throwIfNoEntry: false;
  985. },
  986. ): Stats | undefined;
  987. (
  988. path: PathLike,
  989. options: StatSyncOptions & {
  990. bigint: true;
  991. throwIfNoEntry: false;
  992. },
  993. ): BigIntStats | undefined;
  994. (
  995. path: PathLike,
  996. options?: StatSyncOptions & {
  997. bigint?: false | undefined;
  998. },
  999. ): Stats;
  1000. (
  1001. path: PathLike,
  1002. options: StatSyncOptions & {
  1003. bigint: true;
  1004. },
  1005. ): BigIntStats;
  1006. (
  1007. path: PathLike,
  1008. options: StatSyncOptions & {
  1009. bigint: boolean;
  1010. throwIfNoEntry?: false | undefined;
  1011. },
  1012. ): Stats | BigIntStats;
  1013. (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined;
  1014. }
  1015. /**
  1016. * Synchronous stat(2) - Get file status.
  1017. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1018. */
  1019. export const statSync: StatSyncFn;
  1020. /**
  1021. * Invokes the callback with the `fs.Stats` for the file descriptor.
  1022. *
  1023. * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail.
  1024. * @since v0.1.95
  1025. */
  1026. export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void;
  1027. export function fstat(
  1028. fd: number,
  1029. options:
  1030. | (StatOptions & {
  1031. bigint?: false | undefined;
  1032. })
  1033. | undefined,
  1034. callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void,
  1035. ): void;
  1036. export function fstat(
  1037. fd: number,
  1038. options: StatOptions & {
  1039. bigint: true;
  1040. },
  1041. callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void,
  1042. ): void;
  1043. export function fstat(
  1044. fd: number,
  1045. options: StatOptions | undefined,
  1046. callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void,
  1047. ): void;
  1048. export namespace fstat {
  1049. /**
  1050. * Asynchronous fstat(2) - Get file status.
  1051. * @param fd A file descriptor.
  1052. */
  1053. function __promisify__(
  1054. fd: number,
  1055. options?: StatOptions & {
  1056. bigint?: false | undefined;
  1057. },
  1058. ): Promise<Stats>;
  1059. function __promisify__(
  1060. fd: number,
  1061. options: StatOptions & {
  1062. bigint: true;
  1063. },
  1064. ): Promise<BigIntStats>;
  1065. function __promisify__(fd: number, options?: StatOptions): Promise<Stats | BigIntStats>;
  1066. }
  1067. /**
  1068. * Retrieves the `fs.Stats` for the file descriptor.
  1069. *
  1070. * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail.
  1071. * @since v0.1.95
  1072. */
  1073. export function fstatSync(
  1074. fd: number,
  1075. options?: StatOptions & {
  1076. bigint?: false | undefined;
  1077. },
  1078. ): Stats;
  1079. export function fstatSync(
  1080. fd: number,
  1081. options: StatOptions & {
  1082. bigint: true;
  1083. },
  1084. ): BigIntStats;
  1085. export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats;
  1086. /**
  1087. * Retrieves the `fs.Stats` for the symbolic link referred to by the path.
  1088. * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic
  1089. * link, then the link itself is stat-ed, not the file that it refers to.
  1090. *
  1091. * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details.
  1092. * @since v0.1.30
  1093. */
  1094. export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void;
  1095. export function lstat(
  1096. path: PathLike,
  1097. options:
  1098. | (StatOptions & {
  1099. bigint?: false | undefined;
  1100. })
  1101. | undefined,
  1102. callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void,
  1103. ): void;
  1104. export function lstat(
  1105. path: PathLike,
  1106. options: StatOptions & {
  1107. bigint: true;
  1108. },
  1109. callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void,
  1110. ): void;
  1111. export function lstat(
  1112. path: PathLike,
  1113. options: StatOptions | undefined,
  1114. callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void,
  1115. ): void;
  1116. export namespace lstat {
  1117. /**
  1118. * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links.
  1119. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1120. */
  1121. function __promisify__(
  1122. path: PathLike,
  1123. options?: StatOptions & {
  1124. bigint?: false | undefined;
  1125. },
  1126. ): Promise<Stats>;
  1127. function __promisify__(
  1128. path: PathLike,
  1129. options: StatOptions & {
  1130. bigint: true;
  1131. },
  1132. ): Promise<BigIntStats>;
  1133. function __promisify__(path: PathLike, options?: StatOptions): Promise<Stats | BigIntStats>;
  1134. }
  1135. /**
  1136. * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which
  1137. * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object.
  1138. *
  1139. * In case of an error, the `err.code` will be one of `Common System Errors`.
  1140. * @since v19.6.0, v18.15.0
  1141. * @param path A path to an existing file or directory on the file system to be queried.
  1142. */
  1143. export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void;
  1144. export function statfs(
  1145. path: PathLike,
  1146. options:
  1147. | (StatFsOptions & {
  1148. bigint?: false | undefined;
  1149. })
  1150. | undefined,
  1151. callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void,
  1152. ): void;
  1153. export function statfs(
  1154. path: PathLike,
  1155. options: StatFsOptions & {
  1156. bigint: true;
  1157. },
  1158. callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void,
  1159. ): void;
  1160. export function statfs(
  1161. path: PathLike,
  1162. options: StatFsOptions | undefined,
  1163. callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void,
  1164. ): void;
  1165. export namespace statfs {
  1166. /**
  1167. * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an <fs.StatFs> object.
  1168. * @param path A path to an existing file or directory on the file system to be queried.
  1169. */
  1170. function __promisify__(
  1171. path: PathLike,
  1172. options?: StatFsOptions & {
  1173. bigint?: false | undefined;
  1174. },
  1175. ): Promise<StatsFs>;
  1176. function __promisify__(
  1177. path: PathLike,
  1178. options: StatFsOptions & {
  1179. bigint: true;
  1180. },
  1181. ): Promise<BigIntStatsFs>;
  1182. function __promisify__(path: PathLike, options?: StatFsOptions): Promise<StatsFs | BigIntStatsFs>;
  1183. }
  1184. /**
  1185. * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which
  1186. * contains `path`.
  1187. *
  1188. * In case of an error, the `err.code` will be one of `Common System Errors`.
  1189. * @since v19.6.0, v18.15.0
  1190. * @param path A path to an existing file or directory on the file system to be queried.
  1191. */
  1192. export function statfsSync(
  1193. path: PathLike,
  1194. options?: StatFsOptions & {
  1195. bigint?: false | undefined;
  1196. },
  1197. ): StatsFs;
  1198. export function statfsSync(
  1199. path: PathLike,
  1200. options: StatFsOptions & {
  1201. bigint: true;
  1202. },
  1203. ): BigIntStatsFs;
  1204. export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs;
  1205. /**
  1206. * Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
  1207. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1208. */
  1209. export const lstatSync: StatSyncFn;
  1210. /**
  1211. * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than
  1212. * a possible
  1213. * exception are given to the completion callback.
  1214. * @since v0.1.31
  1215. */
  1216. export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void;
  1217. export namespace link {
  1218. /**
  1219. * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file.
  1220. * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol.
  1221. * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol.
  1222. */
  1223. function __promisify__(existingPath: PathLike, newPath: PathLike): Promise<void>;
  1224. }
  1225. /**
  1226. * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`.
  1227. * @since v0.1.31
  1228. */
  1229. export function linkSync(existingPath: PathLike, newPath: PathLike): void;
  1230. /**
  1231. * Creates the link called `path` pointing to `target`. No arguments other than a
  1232. * possible exception are given to the completion callback.
  1233. *
  1234. * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details.
  1235. *
  1236. * The `type` argument is only available on Windows and ignored on other platforms.
  1237. * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is
  1238. * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`.
  1239. * If the `target` does not exist, `'file'` will be used. Windows junction points
  1240. * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction
  1241. * points on NTFS volumes can only point to directories.
  1242. *
  1243. * Relative targets are relative to the link's parent directory.
  1244. *
  1245. * ```js
  1246. * import { symlink } from 'node:fs';
  1247. *
  1248. * symlink('./mew', './mewtwo', callback);
  1249. * ```
  1250. *
  1251. * The above example creates a symbolic link `mewtwo` which points to `mew` in the
  1252. * same directory:
  1253. *
  1254. * ```bash
  1255. * $ tree .
  1256. * .
  1257. * ├── mew
  1258. * └── mewtwo -> ./mew
  1259. * ```
  1260. * @since v0.1.31
  1261. * @param [type='null']
  1262. */
  1263. export function symlink(
  1264. target: PathLike,
  1265. path: PathLike,
  1266. type: symlink.Type | undefined | null,
  1267. callback: NoParamCallback,
  1268. ): void;
  1269. /**
  1270. * Asynchronous symlink(2) - Create a new symbolic link to an existing file.
  1271. * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol.
  1272. * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol.
  1273. */
  1274. export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void;
  1275. export namespace symlink {
  1276. /**
  1277. * Asynchronous symlink(2) - Create a new symbolic link to an existing file.
  1278. * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol.
  1279. * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol.
  1280. * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms).
  1281. * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path.
  1282. */
  1283. function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise<void>;
  1284. type Type = "dir" | "file" | "junction";
  1285. }
  1286. /**
  1287. * Returns `undefined`.
  1288. *
  1289. * For detailed information, see the documentation of the asynchronous version of
  1290. * this API: {@link symlink}.
  1291. * @since v0.1.31
  1292. * @param [type='null']
  1293. */
  1294. export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void;
  1295. /**
  1296. * Reads the contents of the symbolic link referred to by `path`. The callback gets
  1297. * two arguments `(err, linkString)`.
  1298. *
  1299. * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details.
  1300. *
  1301. * The optional `options` argument can be a string specifying an encoding, or an
  1302. * object with an `encoding` property specifying the character encoding to use for
  1303. * the link path passed to the callback. If the `encoding` is set to `'buffer'`,
  1304. * the link path returned will be passed as a `Buffer` object.
  1305. * @since v0.1.31
  1306. */
  1307. export function readlink(
  1308. path: PathLike,
  1309. options: EncodingOption,
  1310. callback: (err: NodeJS.ErrnoException | null, linkString: string) => void,
  1311. ): void;
  1312. /**
  1313. * Asynchronous readlink(2) - read value of a symbolic link.
  1314. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1315. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1316. */
  1317. export function readlink(
  1318. path: PathLike,
  1319. options: BufferEncodingOption,
  1320. callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void,
  1321. ): void;
  1322. /**
  1323. * Asynchronous readlink(2) - read value of a symbolic link.
  1324. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1325. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1326. */
  1327. export function readlink(
  1328. path: PathLike,
  1329. options: EncodingOption,
  1330. callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void,
  1331. ): void;
  1332. /**
  1333. * Asynchronous readlink(2) - read value of a symbolic link.
  1334. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1335. */
  1336. export function readlink(
  1337. path: PathLike,
  1338. callback: (err: NodeJS.ErrnoException | null, linkString: string) => void,
  1339. ): void;
  1340. export namespace readlink {
  1341. /**
  1342. * Asynchronous readlink(2) - read value of a symbolic link.
  1343. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1344. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1345. */
  1346. function __promisify__(path: PathLike, options?: EncodingOption): Promise<string>;
  1347. /**
  1348. * Asynchronous readlink(2) - read value of a symbolic link.
  1349. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1350. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1351. */
  1352. function __promisify__(path: PathLike, options: BufferEncodingOption): Promise<Buffer>;
  1353. /**
  1354. * Asynchronous readlink(2) - read value of a symbolic link.
  1355. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1356. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1357. */
  1358. function __promisify__(path: PathLike, options?: EncodingOption): Promise<string | Buffer>;
  1359. }
  1360. /**
  1361. * Returns the symbolic link's string value.
  1362. *
  1363. * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details.
  1364. *
  1365. * The optional `options` argument can be a string specifying an encoding, or an
  1366. * object with an `encoding` property specifying the character encoding to use for
  1367. * the link path returned. If the `encoding` is set to `'buffer'`,
  1368. * the link path returned will be passed as a `Buffer` object.
  1369. * @since v0.1.31
  1370. */
  1371. export function readlinkSync(path: PathLike, options?: EncodingOption): string;
  1372. /**
  1373. * Synchronous readlink(2) - read value of a symbolic link.
  1374. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1375. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1376. */
  1377. export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer;
  1378. /**
  1379. * Synchronous readlink(2) - read value of a symbolic link.
  1380. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1381. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1382. */
  1383. export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer;
  1384. /**
  1385. * Asynchronously computes the canonical pathname by resolving `.`, `..`, and
  1386. * symbolic links.
  1387. *
  1388. * A canonical pathname is not necessarily unique. Hard links and bind mounts can
  1389. * expose a file system entity through many pathnames.
  1390. *
  1391. * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions:
  1392. *
  1393. * 1. No case conversion is performed on case-insensitive file systems.
  1394. * 2. The maximum number of symbolic links is platform-independent and generally
  1395. * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports.
  1396. *
  1397. * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths.
  1398. *
  1399. * Only paths that can be converted to UTF8 strings are supported.
  1400. *
  1401. * The optional `options` argument can be a string specifying an encoding, or an
  1402. * object with an `encoding` property specifying the character encoding to use for
  1403. * the path passed to the callback. If the `encoding` is set to `'buffer'`,
  1404. * the path returned will be passed as a `Buffer` object.
  1405. *
  1406. * If `path` resolves to a socket or a pipe, the function will return a system
  1407. * dependent name for that object.
  1408. * @since v0.1.31
  1409. */
  1410. export function realpath(
  1411. path: PathLike,
  1412. options: EncodingOption,
  1413. callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void,
  1414. ): void;
  1415. /**
  1416. * Asynchronous realpath(3) - return the canonicalized absolute pathname.
  1417. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1418. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1419. */
  1420. export function realpath(
  1421. path: PathLike,
  1422. options: BufferEncodingOption,
  1423. callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void,
  1424. ): void;
  1425. /**
  1426. * Asynchronous realpath(3) - return the canonicalized absolute pathname.
  1427. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1428. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1429. */
  1430. export function realpath(
  1431. path: PathLike,
  1432. options: EncodingOption,
  1433. callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void,
  1434. ): void;
  1435. /**
  1436. * Asynchronous realpath(3) - return the canonicalized absolute pathname.
  1437. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1438. */
  1439. export function realpath(
  1440. path: PathLike,
  1441. callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void,
  1442. ): void;
  1443. export namespace realpath {
  1444. /**
  1445. * Asynchronous realpath(3) - return the canonicalized absolute pathname.
  1446. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1447. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1448. */
  1449. function __promisify__(path: PathLike, options?: EncodingOption): Promise<string>;
  1450. /**
  1451. * Asynchronous realpath(3) - return the canonicalized absolute pathname.
  1452. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1453. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1454. */
  1455. function __promisify__(path: PathLike, options: BufferEncodingOption): Promise<Buffer>;
  1456. /**
  1457. * Asynchronous realpath(3) - return the canonicalized absolute pathname.
  1458. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1459. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1460. */
  1461. function __promisify__(path: PathLike, options?: EncodingOption): Promise<string | Buffer>;
  1462. /**
  1463. * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html).
  1464. *
  1465. * The `callback` gets two arguments `(err, resolvedPath)`.
  1466. *
  1467. * Only paths that can be converted to UTF8 strings are supported.
  1468. *
  1469. * The optional `options` argument can be a string specifying an encoding, or an
  1470. * object with an `encoding` property specifying the character encoding to use for
  1471. * the path passed to the callback. If the `encoding` is set to `'buffer'`,
  1472. * the path returned will be passed as a `Buffer` object.
  1473. *
  1474. * On Linux, when Node.js is linked against musl libc, the procfs file system must
  1475. * be mounted on `/proc` in order for this function to work. Glibc does not have
  1476. * this restriction.
  1477. * @since v9.2.0
  1478. */
  1479. function native(
  1480. path: PathLike,
  1481. options: EncodingOption,
  1482. callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void,
  1483. ): void;
  1484. function native(
  1485. path: PathLike,
  1486. options: BufferEncodingOption,
  1487. callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void,
  1488. ): void;
  1489. function native(
  1490. path: PathLike,
  1491. options: EncodingOption,
  1492. callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void,
  1493. ): void;
  1494. function native(
  1495. path: PathLike,
  1496. callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void,
  1497. ): void;
  1498. }
  1499. /**
  1500. * Returns the resolved pathname.
  1501. *
  1502. * For detailed information, see the documentation of the asynchronous version of
  1503. * this API: {@link realpath}.
  1504. * @since v0.1.31
  1505. */
  1506. export function realpathSync(path: PathLike, options?: EncodingOption): string;
  1507. /**
  1508. * Synchronous realpath(3) - return the canonicalized absolute pathname.
  1509. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1510. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1511. */
  1512. export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer;
  1513. /**
  1514. * Synchronous realpath(3) - return the canonicalized absolute pathname.
  1515. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1516. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1517. */
  1518. export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer;
  1519. export namespace realpathSync {
  1520. function native(path: PathLike, options?: EncodingOption): string;
  1521. function native(path: PathLike, options: BufferEncodingOption): Buffer;
  1522. function native(path: PathLike, options?: EncodingOption): string | Buffer;
  1523. }
  1524. /**
  1525. * Asynchronously removes a file or symbolic link. No arguments other than a
  1526. * possible exception are given to the completion callback.
  1527. *
  1528. * ```js
  1529. * import { unlink } from 'node:fs';
  1530. * // Assuming that 'path/file.txt' is a regular file.
  1531. * unlink('path/file.txt', (err) => {
  1532. * if (err) throw err;
  1533. * console.log('path/file.txt was deleted');
  1534. * });
  1535. * ```
  1536. *
  1537. * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a
  1538. * directory, use {@link rmdir}.
  1539. *
  1540. * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details.
  1541. * @since v0.0.2
  1542. */
  1543. export function unlink(path: PathLike, callback: NoParamCallback): void;
  1544. export namespace unlink {
  1545. /**
  1546. * Asynchronous unlink(2) - delete a name and possibly the file it refers to.
  1547. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1548. */
  1549. function __promisify__(path: PathLike): Promise<void>;
  1550. }
  1551. /**
  1552. * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`.
  1553. * @since v0.1.21
  1554. */
  1555. export function unlinkSync(path: PathLike): void;
  1556. export interface RmDirOptions {
  1557. /**
  1558. * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
  1559. * `EPERM` error is encountered, Node.js will retry the operation with a linear
  1560. * backoff wait of `retryDelay` ms longer on each try. This option represents the
  1561. * number of retries. This option is ignored if the `recursive` option is not
  1562. * `true`.
  1563. * @default 0
  1564. */
  1565. maxRetries?: number | undefined;
  1566. /**
  1567. * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning
  1568. * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file.
  1569. * Use `fs.rm(path, { recursive: true, force: true })` instead.
  1570. *
  1571. * If `true`, perform a recursive directory removal. In
  1572. * recursive mode, operations are retried on failure.
  1573. * @default false
  1574. */
  1575. recursive?: boolean | undefined;
  1576. /**
  1577. * The amount of time in milliseconds to wait between retries.
  1578. * This option is ignored if the `recursive` option is not `true`.
  1579. * @default 100
  1580. */
  1581. retryDelay?: number | undefined;
  1582. }
  1583. /**
  1584. * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given
  1585. * to the completion callback.
  1586. *
  1587. * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on
  1588. * Windows and an `ENOTDIR` error on POSIX.
  1589. *
  1590. * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`.
  1591. * @since v0.0.2
  1592. */
  1593. export function rmdir(path: PathLike, callback: NoParamCallback): void;
  1594. export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void;
  1595. export namespace rmdir {
  1596. /**
  1597. * Asynchronous rmdir(2) - delete a directory.
  1598. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1599. */
  1600. function __promisify__(path: PathLike, options?: RmDirOptions): Promise<void>;
  1601. }
  1602. /**
  1603. * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`.
  1604. *
  1605. * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error
  1606. * on Windows and an `ENOTDIR` error on POSIX.
  1607. *
  1608. * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`.
  1609. * @since v0.1.21
  1610. */
  1611. export function rmdirSync(path: PathLike, options?: RmDirOptions): void;
  1612. export interface RmOptions {
  1613. /**
  1614. * When `true`, exceptions will be ignored if `path` does not exist.
  1615. * @default false
  1616. */
  1617. force?: boolean | undefined;
  1618. /**
  1619. * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
  1620. * `EPERM` error is encountered, Node.js will retry the operation with a linear
  1621. * backoff wait of `retryDelay` ms longer on each try. This option represents the
  1622. * number of retries. This option is ignored if the `recursive` option is not
  1623. * `true`.
  1624. * @default 0
  1625. */
  1626. maxRetries?: number | undefined;
  1627. /**
  1628. * If `true`, perform a recursive directory removal. In
  1629. * recursive mode, operations are retried on failure.
  1630. * @default false
  1631. */
  1632. recursive?: boolean | undefined;
  1633. /**
  1634. * The amount of time in milliseconds to wait between retries.
  1635. * This option is ignored if the `recursive` option is not `true`.
  1636. * @default 100
  1637. */
  1638. retryDelay?: number | undefined;
  1639. }
  1640. /**
  1641. * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the
  1642. * completion callback.
  1643. * @since v14.14.0
  1644. */
  1645. export function rm(path: PathLike, callback: NoParamCallback): void;
  1646. export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void;
  1647. export namespace rm {
  1648. /**
  1649. * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility).
  1650. */
  1651. function __promisify__(path: PathLike, options?: RmOptions): Promise<void>;
  1652. }
  1653. /**
  1654. * Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`.
  1655. * @since v14.14.0
  1656. */
  1657. export function rmSync(path: PathLike, options?: RmOptions): void;
  1658. export interface MakeDirectoryOptions {
  1659. /**
  1660. * Indicates whether parent folders should be created.
  1661. * If a folder was created, the path to the first created folder will be returned.
  1662. * @default false
  1663. */
  1664. recursive?: boolean | undefined;
  1665. /**
  1666. * A file mode. If a string is passed, it is parsed as an octal integer. If not specified
  1667. * @default 0o777
  1668. */
  1669. mode?: Mode | undefined;
  1670. }
  1671. /**
  1672. * Asynchronously creates a directory.
  1673. *
  1674. * The callback is given a possible exception and, if `recursive` is `true`, the
  1675. * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was
  1676. * created (for instance, if it was previously created).
  1677. *
  1678. * The optional `options` argument can be an integer specifying `mode` (permission
  1679. * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that
  1680. * exists results in an error only
  1681. * when `recursive` is false. If `recursive` is false and the directory exists,
  1682. * an `EEXIST` error occurs.
  1683. *
  1684. * ```js
  1685. * import { mkdir } from 'node:fs';
  1686. *
  1687. * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist.
  1688. * mkdir('./tmp/a/apple', { recursive: true }, (err) => {
  1689. * if (err) throw err;
  1690. * });
  1691. * ```
  1692. *
  1693. * On Windows, using `fs.mkdir()` on the root directory even with recursion will
  1694. * result in an error:
  1695. *
  1696. * ```js
  1697. * import { mkdir } from 'node:fs';
  1698. *
  1699. * mkdir('/', { recursive: true }, (err) => {
  1700. * // => [Error: EPERM: operation not permitted, mkdir 'C:\']
  1701. * });
  1702. * ```
  1703. *
  1704. * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details.
  1705. * @since v0.1.8
  1706. */
  1707. export function mkdir(
  1708. path: PathLike,
  1709. options: MakeDirectoryOptions & {
  1710. recursive: true;
  1711. },
  1712. callback: (err: NodeJS.ErrnoException | null, path?: string) => void,
  1713. ): void;
  1714. /**
  1715. * Asynchronous mkdir(2) - create a directory.
  1716. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1717. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
  1718. * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
  1719. */
  1720. export function mkdir(
  1721. path: PathLike,
  1722. options:
  1723. | Mode
  1724. | (MakeDirectoryOptions & {
  1725. recursive?: false | undefined;
  1726. })
  1727. | null
  1728. | undefined,
  1729. callback: NoParamCallback,
  1730. ): void;
  1731. /**
  1732. * Asynchronous mkdir(2) - create a directory.
  1733. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1734. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
  1735. * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
  1736. */
  1737. export function mkdir(
  1738. path: PathLike,
  1739. options: Mode | MakeDirectoryOptions | null | undefined,
  1740. callback: (err: NodeJS.ErrnoException | null, path?: string) => void,
  1741. ): void;
  1742. /**
  1743. * Asynchronous mkdir(2) - create a directory with a mode of `0o777`.
  1744. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1745. */
  1746. export function mkdir(path: PathLike, callback: NoParamCallback): void;
  1747. export namespace mkdir {
  1748. /**
  1749. * Asynchronous mkdir(2) - create a directory.
  1750. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1751. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
  1752. * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
  1753. */
  1754. function __promisify__(
  1755. path: PathLike,
  1756. options: MakeDirectoryOptions & {
  1757. recursive: true;
  1758. },
  1759. ): Promise<string | undefined>;
  1760. /**
  1761. * Asynchronous mkdir(2) - create a directory.
  1762. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1763. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
  1764. * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
  1765. */
  1766. function __promisify__(
  1767. path: PathLike,
  1768. options?:
  1769. | Mode
  1770. | (MakeDirectoryOptions & {
  1771. recursive?: false | undefined;
  1772. })
  1773. | null,
  1774. ): Promise<void>;
  1775. /**
  1776. * Asynchronous mkdir(2) - create a directory.
  1777. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1778. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
  1779. * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
  1780. */
  1781. function __promisify__(
  1782. path: PathLike,
  1783. options?: Mode | MakeDirectoryOptions | null,
  1784. ): Promise<string | undefined>;
  1785. }
  1786. /**
  1787. * Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created.
  1788. * This is the synchronous version of {@link mkdir}.
  1789. *
  1790. * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details.
  1791. * @since v0.1.21
  1792. */
  1793. export function mkdirSync(
  1794. path: PathLike,
  1795. options: MakeDirectoryOptions & {
  1796. recursive: true;
  1797. },
  1798. ): string | undefined;
  1799. /**
  1800. * Synchronous mkdir(2) - create a directory.
  1801. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1802. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
  1803. * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
  1804. */
  1805. export function mkdirSync(
  1806. path: PathLike,
  1807. options?:
  1808. | Mode
  1809. | (MakeDirectoryOptions & {
  1810. recursive?: false | undefined;
  1811. })
  1812. | null,
  1813. ): void;
  1814. /**
  1815. * Synchronous mkdir(2) - create a directory.
  1816. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1817. * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
  1818. * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
  1819. */
  1820. export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined;
  1821. /**
  1822. * Creates a unique temporary directory.
  1823. *
  1824. * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform
  1825. * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms,
  1826. * notably the BSDs, can return more than six random characters, and replace
  1827. * trailing `X` characters in `prefix` with random characters.
  1828. *
  1829. * The created directory path is passed as a string to the callback's second
  1830. * parameter.
  1831. *
  1832. * The optional `options` argument can be a string specifying an encoding, or an
  1833. * object with an `encoding` property specifying the character encoding to use.
  1834. *
  1835. * ```js
  1836. * import { mkdtemp } from 'node:fs';
  1837. * import { join } from 'node:path';
  1838. * import { tmpdir } from 'node:os';
  1839. *
  1840. * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {
  1841. * if (err) throw err;
  1842. * console.log(directory);
  1843. * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
  1844. * });
  1845. * ```
  1846. *
  1847. * The `fs.mkdtemp()` method will append the six randomly selected characters
  1848. * directly to the `prefix` string. For instance, given a directory `/tmp`, if the
  1849. * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator
  1850. * (`import { sep } from 'node:path'`).
  1851. *
  1852. * ```js
  1853. * import { tmpdir } from 'node:os';
  1854. * import { mkdtemp } from 'node:fs';
  1855. *
  1856. * // The parent directory for the new temporary directory
  1857. * const tmpDir = tmpdir();
  1858. *
  1859. * // This method is *INCORRECT*:
  1860. * mkdtemp(tmpDir, (err, directory) => {
  1861. * if (err) throw err;
  1862. * console.log(directory);
  1863. * // Will print something similar to `/tmpabc123`.
  1864. * // A new temporary directory is created at the file system root
  1865. * // rather than *within* the /tmp directory.
  1866. * });
  1867. *
  1868. * // This method is *CORRECT*:
  1869. * import { sep } from 'node:path';
  1870. * mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
  1871. * if (err) throw err;
  1872. * console.log(directory);
  1873. * // Will print something similar to `/tmp/abc123`.
  1874. * // A new temporary directory is created within
  1875. * // the /tmp directory.
  1876. * });
  1877. * ```
  1878. * @since v5.10.0
  1879. */
  1880. export function mkdtemp(
  1881. prefix: string,
  1882. options: EncodingOption,
  1883. callback: (err: NodeJS.ErrnoException | null, folder: string) => void,
  1884. ): void;
  1885. /**
  1886. * Asynchronously creates a unique temporary directory.
  1887. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
  1888. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1889. */
  1890. export function mkdtemp(
  1891. prefix: string,
  1892. options:
  1893. | "buffer"
  1894. | {
  1895. encoding: "buffer";
  1896. },
  1897. callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void,
  1898. ): void;
  1899. /**
  1900. * Asynchronously creates a unique temporary directory.
  1901. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
  1902. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1903. */
  1904. export function mkdtemp(
  1905. prefix: string,
  1906. options: EncodingOption,
  1907. callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void,
  1908. ): void;
  1909. /**
  1910. * Asynchronously creates a unique temporary directory.
  1911. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
  1912. */
  1913. export function mkdtemp(
  1914. prefix: string,
  1915. callback: (err: NodeJS.ErrnoException | null, folder: string) => void,
  1916. ): void;
  1917. export namespace mkdtemp {
  1918. /**
  1919. * Asynchronously creates a unique temporary directory.
  1920. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
  1921. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1922. */
  1923. function __promisify__(prefix: string, options?: EncodingOption): Promise<string>;
  1924. /**
  1925. * Asynchronously creates a unique temporary directory.
  1926. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
  1927. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1928. */
  1929. function __promisify__(prefix: string, options: BufferEncodingOption): Promise<Buffer>;
  1930. /**
  1931. * Asynchronously creates a unique temporary directory.
  1932. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
  1933. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1934. */
  1935. function __promisify__(prefix: string, options?: EncodingOption): Promise<string | Buffer>;
  1936. }
  1937. /**
  1938. * Returns the created directory path.
  1939. *
  1940. * For detailed information, see the documentation of the asynchronous version of
  1941. * this API: {@link mkdtemp}.
  1942. *
  1943. * The optional `options` argument can be a string specifying an encoding, or an
  1944. * object with an `encoding` property specifying the character encoding to use.
  1945. * @since v5.10.0
  1946. */
  1947. export function mkdtempSync(prefix: string, options?: EncodingOption): string;
  1948. /**
  1949. * Synchronously creates a unique temporary directory.
  1950. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
  1951. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1952. */
  1953. export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer;
  1954. /**
  1955. * Synchronously creates a unique temporary directory.
  1956. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
  1957. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1958. */
  1959. export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer;
  1960. /**
  1961. * Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`.
  1962. *
  1963. * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details.
  1964. *
  1965. * The optional `options` argument can be a string specifying an encoding, or an
  1966. * object with an `encoding` property specifying the character encoding to use for
  1967. * the filenames passed to the callback. If the `encoding` is set to `'buffer'`,
  1968. * the filenames returned will be passed as `Buffer` objects.
  1969. *
  1970. * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects.
  1971. * @since v0.1.8
  1972. */
  1973. export function readdir(
  1974. path: PathLike,
  1975. options:
  1976. | {
  1977. encoding: BufferEncoding | null;
  1978. withFileTypes?: false | undefined;
  1979. recursive?: boolean | undefined;
  1980. }
  1981. | BufferEncoding
  1982. | undefined
  1983. | null,
  1984. callback: (err: NodeJS.ErrnoException | null, files: string[]) => void,
  1985. ): void;
  1986. /**
  1987. * Asynchronous readdir(3) - read a directory.
  1988. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  1989. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  1990. */
  1991. export function readdir(
  1992. path: PathLike,
  1993. options:
  1994. | {
  1995. encoding: "buffer";
  1996. withFileTypes?: false | undefined;
  1997. recursive?: boolean | undefined;
  1998. }
  1999. | "buffer",
  2000. callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void,
  2001. ): void;
  2002. /**
  2003. * Asynchronous readdir(3) - read a directory.
  2004. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2005. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  2006. */
  2007. export function readdir(
  2008. path: PathLike,
  2009. options:
  2010. | (ObjectEncodingOptions & {
  2011. withFileTypes?: false | undefined;
  2012. recursive?: boolean | undefined;
  2013. })
  2014. | BufferEncoding
  2015. | undefined
  2016. | null,
  2017. callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void,
  2018. ): void;
  2019. /**
  2020. * Asynchronous readdir(3) - read a directory.
  2021. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2022. */
  2023. export function readdir(
  2024. path: PathLike,
  2025. callback: (err: NodeJS.ErrnoException | null, files: string[]) => void,
  2026. ): void;
  2027. /**
  2028. * Asynchronous readdir(3) - read a directory.
  2029. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2030. * @param options If called with `withFileTypes: true` the result data will be an array of Dirent.
  2031. */
  2032. export function readdir(
  2033. path: PathLike,
  2034. options: ObjectEncodingOptions & {
  2035. withFileTypes: true;
  2036. recursive?: boolean | undefined;
  2037. },
  2038. callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void,
  2039. ): void;
  2040. /**
  2041. * Asynchronous readdir(3) - read a directory.
  2042. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2043. * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`.
  2044. */
  2045. export function readdir(
  2046. path: PathLike,
  2047. options: {
  2048. encoding: "buffer";
  2049. withFileTypes: true;
  2050. recursive?: boolean | undefined;
  2051. },
  2052. callback: (err: NodeJS.ErrnoException | null, files: Dirent<Buffer>[]) => void,
  2053. ): void;
  2054. export namespace readdir {
  2055. /**
  2056. * Asynchronous readdir(3) - read a directory.
  2057. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2058. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  2059. */
  2060. function __promisify__(
  2061. path: PathLike,
  2062. options?:
  2063. | {
  2064. encoding: BufferEncoding | null;
  2065. withFileTypes?: false | undefined;
  2066. recursive?: boolean | undefined;
  2067. }
  2068. | BufferEncoding
  2069. | null,
  2070. ): Promise<string[]>;
  2071. /**
  2072. * Asynchronous readdir(3) - read a directory.
  2073. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2074. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  2075. */
  2076. function __promisify__(
  2077. path: PathLike,
  2078. options:
  2079. | "buffer"
  2080. | {
  2081. encoding: "buffer";
  2082. withFileTypes?: false | undefined;
  2083. recursive?: boolean | undefined;
  2084. },
  2085. ): Promise<Buffer[]>;
  2086. /**
  2087. * Asynchronous readdir(3) - read a directory.
  2088. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2089. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  2090. */
  2091. function __promisify__(
  2092. path: PathLike,
  2093. options?:
  2094. | (ObjectEncodingOptions & {
  2095. withFileTypes?: false | undefined;
  2096. recursive?: boolean | undefined;
  2097. })
  2098. | BufferEncoding
  2099. | null,
  2100. ): Promise<string[] | Buffer[]>;
  2101. /**
  2102. * Asynchronous readdir(3) - read a directory.
  2103. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2104. * @param options If called with `withFileTypes: true` the result data will be an array of Dirent
  2105. */
  2106. function __promisify__(
  2107. path: PathLike,
  2108. options: ObjectEncodingOptions & {
  2109. withFileTypes: true;
  2110. recursive?: boolean | undefined;
  2111. },
  2112. ): Promise<Dirent[]>;
  2113. /**
  2114. * Asynchronous readdir(3) - read a directory.
  2115. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2116. * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`.
  2117. */
  2118. function __promisify__(
  2119. path: PathLike,
  2120. options: {
  2121. encoding: "buffer";
  2122. withFileTypes: true;
  2123. recursive?: boolean | undefined;
  2124. },
  2125. ): Promise<Dirent<Buffer>[]>;
  2126. }
  2127. /**
  2128. * Reads the contents of the directory.
  2129. *
  2130. * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details.
  2131. *
  2132. * The optional `options` argument can be a string specifying an encoding, or an
  2133. * object with an `encoding` property specifying the character encoding to use for
  2134. * the filenames returned. If the `encoding` is set to `'buffer'`,
  2135. * the filenames returned will be passed as `Buffer` objects.
  2136. *
  2137. * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects.
  2138. * @since v0.1.21
  2139. */
  2140. export function readdirSync(
  2141. path: PathLike,
  2142. options?:
  2143. | {
  2144. encoding: BufferEncoding | null;
  2145. withFileTypes?: false | undefined;
  2146. recursive?: boolean | undefined;
  2147. }
  2148. | BufferEncoding
  2149. | null,
  2150. ): string[];
  2151. /**
  2152. * Synchronous readdir(3) - read a directory.
  2153. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2154. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  2155. */
  2156. export function readdirSync(
  2157. path: PathLike,
  2158. options:
  2159. | {
  2160. encoding: "buffer";
  2161. withFileTypes?: false | undefined;
  2162. recursive?: boolean | undefined;
  2163. }
  2164. | "buffer",
  2165. ): Buffer[];
  2166. /**
  2167. * Synchronous readdir(3) - read a directory.
  2168. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2169. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
  2170. */
  2171. export function readdirSync(
  2172. path: PathLike,
  2173. options?:
  2174. | (ObjectEncodingOptions & {
  2175. withFileTypes?: false | undefined;
  2176. recursive?: boolean | undefined;
  2177. })
  2178. | BufferEncoding
  2179. | null,
  2180. ): string[] | Buffer[];
  2181. /**
  2182. * Synchronous readdir(3) - read a directory.
  2183. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2184. * @param options If called with `withFileTypes: true` the result data will be an array of Dirent.
  2185. */
  2186. export function readdirSync(
  2187. path: PathLike,
  2188. options: ObjectEncodingOptions & {
  2189. withFileTypes: true;
  2190. recursive?: boolean | undefined;
  2191. },
  2192. ): Dirent[];
  2193. /**
  2194. * Synchronous readdir(3) - read a directory.
  2195. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2196. * @param options Must include `withFileTypes: true` and `encoding: 'buffer'`.
  2197. */
  2198. export function readdirSync(
  2199. path: PathLike,
  2200. options: {
  2201. encoding: "buffer";
  2202. withFileTypes: true;
  2203. recursive?: boolean | undefined;
  2204. },
  2205. ): Dirent<Buffer>[];
  2206. /**
  2207. * Closes the file descriptor. No arguments other than a possible exception are
  2208. * given to the completion callback.
  2209. *
  2210. * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use
  2211. * through any other `fs` operation may lead to undefined behavior.
  2212. *
  2213. * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail.
  2214. * @since v0.0.2
  2215. */
  2216. export function close(fd: number, callback?: NoParamCallback): void;
  2217. export namespace close {
  2218. /**
  2219. * Asynchronous close(2) - close a file descriptor.
  2220. * @param fd A file descriptor.
  2221. */
  2222. function __promisify__(fd: number): Promise<void>;
  2223. }
  2224. /**
  2225. * Closes the file descriptor. Returns `undefined`.
  2226. *
  2227. * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use
  2228. * through any other `fs` operation may lead to undefined behavior.
  2229. *
  2230. * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail.
  2231. * @since v0.1.21
  2232. */
  2233. export function closeSync(fd: number): void;
  2234. /**
  2235. * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details.
  2236. *
  2237. * `mode` sets the file mode (permission and sticky bits), but only if the file was
  2238. * created. On Windows, only the write permission can be manipulated; see {@link chmod}.
  2239. *
  2240. * The callback gets two arguments `(err, fd)`.
  2241. *
  2242. * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented
  2243. * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains
  2244. * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams).
  2245. *
  2246. * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc.
  2247. * @since v0.0.2
  2248. * @param [flags='r'] See `support of file system `flags``.
  2249. * @param [mode=0o666]
  2250. */
  2251. export function open(
  2252. path: PathLike,
  2253. flags: OpenMode | undefined,
  2254. mode: Mode | undefined | null,
  2255. callback: (err: NodeJS.ErrnoException | null, fd: number) => void,
  2256. ): void;
  2257. /**
  2258. * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`.
  2259. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2260. * @param [flags='r'] See `support of file system `flags``.
  2261. */
  2262. export function open(
  2263. path: PathLike,
  2264. flags: OpenMode | undefined,
  2265. callback: (err: NodeJS.ErrnoException | null, fd: number) => void,
  2266. ): void;
  2267. /**
  2268. * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`.
  2269. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2270. */
  2271. export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void;
  2272. export namespace open {
  2273. /**
  2274. * Asynchronous open(2) - open and possibly create a file.
  2275. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2276. * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`.
  2277. */
  2278. function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise<number>;
  2279. }
  2280. /**
  2281. * Returns an integer representing the file descriptor.
  2282. *
  2283. * For detailed information, see the documentation of the asynchronous version of
  2284. * this API: {@link open}.
  2285. * @since v0.1.21
  2286. * @param [flags='r']
  2287. * @param [mode=0o666]
  2288. */
  2289. export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number;
  2290. /**
  2291. * Change the file system timestamps of the object referenced by `path`.
  2292. *
  2293. * The `atime` and `mtime` arguments follow these rules:
  2294. *
  2295. * * Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`.
  2296. * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown.
  2297. * @since v0.4.2
  2298. */
  2299. export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void;
  2300. export namespace utimes {
  2301. /**
  2302. * Asynchronously change file timestamps of the file referenced by the supplied path.
  2303. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2304. * @param atime The last access time. If a string is provided, it will be coerced to number.
  2305. * @param mtime The last modified time. If a string is provided, it will be coerced to number.
  2306. */
  2307. function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise<void>;
  2308. }
  2309. /**
  2310. * Returns `undefined`.
  2311. *
  2312. * For detailed information, see the documentation of the asynchronous version of
  2313. * this API: {@link utimes}.
  2314. * @since v0.4.2
  2315. */
  2316. export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void;
  2317. /**
  2318. * Change the file system timestamps of the object referenced by the supplied file
  2319. * descriptor. See {@link utimes}.
  2320. * @since v0.4.2
  2321. */
  2322. export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void;
  2323. export namespace futimes {
  2324. /**
  2325. * Asynchronously change file timestamps of the file referenced by the supplied file descriptor.
  2326. * @param fd A file descriptor.
  2327. * @param atime The last access time. If a string is provided, it will be coerced to number.
  2328. * @param mtime The last modified time. If a string is provided, it will be coerced to number.
  2329. */
  2330. function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise<void>;
  2331. }
  2332. /**
  2333. * Synchronous version of {@link futimes}. Returns `undefined`.
  2334. * @since v0.4.2
  2335. */
  2336. export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void;
  2337. /**
  2338. * Request that all data for the open file descriptor is flushed to the storage
  2339. * device. The specific implementation is operating system and device specific.
  2340. * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other
  2341. * than a possible exception are given to the completion callback.
  2342. * @since v0.1.96
  2343. */
  2344. export function fsync(fd: number, callback: NoParamCallback): void;
  2345. export namespace fsync {
  2346. /**
  2347. * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device.
  2348. * @param fd A file descriptor.
  2349. */
  2350. function __promisify__(fd: number): Promise<void>;
  2351. }
  2352. /**
  2353. * Request that all data for the open file descriptor is flushed to the storage
  2354. * device. The specific implementation is operating system and device specific.
  2355. * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`.
  2356. * @since v0.1.96
  2357. */
  2358. export function fsyncSync(fd: number): void;
  2359. export interface WriteOptions {
  2360. /**
  2361. * @default 0
  2362. */
  2363. offset?: number | undefined;
  2364. /**
  2365. * @default `buffer.byteLength - offset`
  2366. */
  2367. length?: number | undefined;
  2368. /**
  2369. * @default null
  2370. */
  2371. position?: number | undefined | null;
  2372. }
  2373. /**
  2374. * Write `buffer` to the file specified by `fd`.
  2375. *
  2376. * `offset` determines the part of the buffer to be written, and `length` is
  2377. * an integer specifying the number of bytes to write.
  2378. *
  2379. * `position` refers to the offset from the beginning of the file where this data
  2380. * should be written. If `typeof position !== 'number'`, the data will be written
  2381. * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html).
  2382. *
  2383. * The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many _bytes_ were written from `buffer`.
  2384. *
  2385. * If this method is invoked as its `util.promisify()` ed version, it returns
  2386. * a promise for an `Object` with `bytesWritten` and `buffer` properties.
  2387. *
  2388. * It is unsafe to use `fs.write()` multiple times on the same file without waiting
  2389. * for the callback. For this scenario, {@link createWriteStream} is
  2390. * recommended.
  2391. *
  2392. * On Linux, positional writes don't work when the file is opened in append mode.
  2393. * The kernel ignores the position argument and always appends the data to
  2394. * the end of the file.
  2395. * @since v0.0.2
  2396. * @param [offset=0]
  2397. * @param [length=buffer.byteLength - offset]
  2398. * @param [position='null']
  2399. */
  2400. export function write<TBuffer extends NodeJS.ArrayBufferView>(
  2401. fd: number,
  2402. buffer: TBuffer,
  2403. offset: number | undefined | null,
  2404. length: number | undefined | null,
  2405. position: number | undefined | null,
  2406. callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void,
  2407. ): void;
  2408. /**
  2409. * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
  2410. * @param fd A file descriptor.
  2411. * @param offset The part of the buffer to be written. If not supplied, defaults to `0`.
  2412. * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`.
  2413. */
  2414. export function write<TBuffer extends NodeJS.ArrayBufferView>(
  2415. fd: number,
  2416. buffer: TBuffer,
  2417. offset: number | undefined | null,
  2418. length: number | undefined | null,
  2419. callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void,
  2420. ): void;
  2421. /**
  2422. * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
  2423. * @param fd A file descriptor.
  2424. * @param offset The part of the buffer to be written. If not supplied, defaults to `0`.
  2425. */
  2426. export function write<TBuffer extends NodeJS.ArrayBufferView>(
  2427. fd: number,
  2428. buffer: TBuffer,
  2429. offset: number | undefined | null,
  2430. callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void,
  2431. ): void;
  2432. /**
  2433. * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
  2434. * @param fd A file descriptor.
  2435. */
  2436. export function write<TBuffer extends NodeJS.ArrayBufferView>(
  2437. fd: number,
  2438. buffer: TBuffer,
  2439. callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void,
  2440. ): void;
  2441. /**
  2442. * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
  2443. * @param fd A file descriptor.
  2444. * @param options An object with the following properties:
  2445. * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`.
  2446. * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`.
  2447. * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
  2448. */
  2449. export function write<TBuffer extends NodeJS.ArrayBufferView>(
  2450. fd: number,
  2451. buffer: TBuffer,
  2452. options: WriteOptions,
  2453. callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void,
  2454. ): void;
  2455. /**
  2456. * Asynchronously writes `string` to the file referenced by the supplied file descriptor.
  2457. * @param fd A file descriptor.
  2458. * @param string A string to write.
  2459. * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
  2460. * @param encoding The expected string encoding.
  2461. */
  2462. export function write(
  2463. fd: number,
  2464. string: string,
  2465. position: number | undefined | null,
  2466. encoding: BufferEncoding | undefined | null,
  2467. callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void,
  2468. ): void;
  2469. /**
  2470. * Asynchronously writes `string` to the file referenced by the supplied file descriptor.
  2471. * @param fd A file descriptor.
  2472. * @param string A string to write.
  2473. * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
  2474. */
  2475. export function write(
  2476. fd: number,
  2477. string: string,
  2478. position: number | undefined | null,
  2479. callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void,
  2480. ): void;
  2481. /**
  2482. * Asynchronously writes `string` to the file referenced by the supplied file descriptor.
  2483. * @param fd A file descriptor.
  2484. * @param string A string to write.
  2485. */
  2486. export function write(
  2487. fd: number,
  2488. string: string,
  2489. callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void,
  2490. ): void;
  2491. export namespace write {
  2492. /**
  2493. * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
  2494. * @param fd A file descriptor.
  2495. * @param offset The part of the buffer to be written. If not supplied, defaults to `0`.
  2496. * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`.
  2497. * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
  2498. */
  2499. function __promisify__<TBuffer extends NodeJS.ArrayBufferView>(
  2500. fd: number,
  2501. buffer?: TBuffer,
  2502. offset?: number,
  2503. length?: number,
  2504. position?: number | null,
  2505. ): Promise<{
  2506. bytesWritten: number;
  2507. buffer: TBuffer;
  2508. }>;
  2509. /**
  2510. * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
  2511. * @param fd A file descriptor.
  2512. * @param options An object with the following properties:
  2513. * * `offset` The part of the buffer to be written. If not supplied, defaults to `0`.
  2514. * * `length` The number of bytes to write. If not supplied, defaults to `buffer.length - offset`.
  2515. * * `position` The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
  2516. */
  2517. function __promisify__<TBuffer extends NodeJS.ArrayBufferView>(
  2518. fd: number,
  2519. buffer?: TBuffer,
  2520. options?: WriteOptions,
  2521. ): Promise<{
  2522. bytesWritten: number;
  2523. buffer: TBuffer;
  2524. }>;
  2525. /**
  2526. * Asynchronously writes `string` to the file referenced by the supplied file descriptor.
  2527. * @param fd A file descriptor.
  2528. * @param string A string to write.
  2529. * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
  2530. * @param encoding The expected string encoding.
  2531. */
  2532. function __promisify__(
  2533. fd: number,
  2534. string: string,
  2535. position?: number | null,
  2536. encoding?: BufferEncoding | null,
  2537. ): Promise<{
  2538. bytesWritten: number;
  2539. buffer: string;
  2540. }>;
  2541. }
  2542. /**
  2543. * For detailed information, see the documentation of the asynchronous version of
  2544. * this API: {@link write}.
  2545. * @since v0.1.21
  2546. * @param [offset=0]
  2547. * @param [length=buffer.byteLength - offset]
  2548. * @param [position='null']
  2549. * @return The number of bytes written.
  2550. */
  2551. export function writeSync(
  2552. fd: number,
  2553. buffer: NodeJS.ArrayBufferView,
  2554. offset?: number | null,
  2555. length?: number | null,
  2556. position?: number | null,
  2557. ): number;
  2558. /**
  2559. * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written.
  2560. * @param fd A file descriptor.
  2561. * @param string A string to write.
  2562. * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
  2563. * @param encoding The expected string encoding.
  2564. */
  2565. export function writeSync(
  2566. fd: number,
  2567. string: string,
  2568. position?: number | null,
  2569. encoding?: BufferEncoding | null,
  2570. ): number;
  2571. export type ReadPosition = number | bigint;
  2572. export interface ReadSyncOptions {
  2573. /**
  2574. * @default 0
  2575. */
  2576. offset?: number | undefined;
  2577. /**
  2578. * @default `length of buffer`
  2579. */
  2580. length?: number | undefined;
  2581. /**
  2582. * @default null
  2583. */
  2584. position?: ReadPosition | null | undefined;
  2585. }
  2586. export interface ReadAsyncOptions<TBuffer extends NodeJS.ArrayBufferView> extends ReadSyncOptions {
  2587. buffer?: TBuffer;
  2588. }
  2589. /**
  2590. * Read data from the file specified by `fd`.
  2591. *
  2592. * The callback is given the three arguments, `(err, bytesRead, buffer)`.
  2593. *
  2594. * If the file is not modified concurrently, the end-of-file is reached when the
  2595. * number of bytes read is zero.
  2596. *
  2597. * If this method is invoked as its `util.promisify()` ed version, it returns
  2598. * a promise for an `Object` with `bytesRead` and `buffer` properties.
  2599. * @since v0.0.2
  2600. * @param buffer The buffer that the data will be written to.
  2601. * @param offset The position in `buffer` to write the data to.
  2602. * @param length The number of bytes to read.
  2603. * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If
  2604. * `position` is an integer, the file position will be unchanged.
  2605. */
  2606. export function read<TBuffer extends NodeJS.ArrayBufferView>(
  2607. fd: number,
  2608. buffer: TBuffer,
  2609. offset: number,
  2610. length: number,
  2611. position: ReadPosition | null,
  2612. callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void,
  2613. ): void;
  2614. /**
  2615. * Similar to the above `fs.read` function, this version takes an optional `options` object.
  2616. * If not otherwise specified in an `options` object,
  2617. * `buffer` defaults to `Buffer.alloc(16384)`,
  2618. * `offset` defaults to `0`,
  2619. * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0
  2620. * `position` defaults to `null`
  2621. * @since v12.17.0, 13.11.0
  2622. */
  2623. export function read<TBuffer extends NodeJS.ArrayBufferView>(
  2624. fd: number,
  2625. options: ReadAsyncOptions<TBuffer>,
  2626. callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void,
  2627. ): void;
  2628. export function read<TBuffer extends NodeJS.ArrayBufferView>(
  2629. fd: number,
  2630. buffer: TBuffer,
  2631. options: ReadSyncOptions,
  2632. callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void,
  2633. ): void;
  2634. export function read<TBuffer extends NodeJS.ArrayBufferView>(
  2635. fd: number,
  2636. buffer: TBuffer,
  2637. callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void,
  2638. ): void;
  2639. export function read(
  2640. fd: number,
  2641. callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void,
  2642. ): void;
  2643. export namespace read {
  2644. /**
  2645. * @param fd A file descriptor.
  2646. * @param buffer The buffer that the data will be written to.
  2647. * @param offset The offset in the buffer at which to start writing.
  2648. * @param length The number of bytes to read.
  2649. * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position.
  2650. */
  2651. function __promisify__<TBuffer extends NodeJS.ArrayBufferView>(
  2652. fd: number,
  2653. buffer: TBuffer,
  2654. offset: number,
  2655. length: number,
  2656. position: number | null,
  2657. ): Promise<{
  2658. bytesRead: number;
  2659. buffer: TBuffer;
  2660. }>;
  2661. function __promisify__<TBuffer extends NodeJS.ArrayBufferView>(
  2662. fd: number,
  2663. options: ReadAsyncOptions<TBuffer>,
  2664. ): Promise<{
  2665. bytesRead: number;
  2666. buffer: TBuffer;
  2667. }>;
  2668. function __promisify__(fd: number): Promise<{
  2669. bytesRead: number;
  2670. buffer: NodeJS.ArrayBufferView;
  2671. }>;
  2672. }
  2673. /**
  2674. * Returns the number of `bytesRead`.
  2675. *
  2676. * For detailed information, see the documentation of the asynchronous version of
  2677. * this API: {@link read}.
  2678. * @since v0.1.21
  2679. * @param [position='null']
  2680. */
  2681. export function readSync(
  2682. fd: number,
  2683. buffer: NodeJS.ArrayBufferView,
  2684. offset: number,
  2685. length: number,
  2686. position: ReadPosition | null,
  2687. ): number;
  2688. /**
  2689. * Similar to the above `fs.readSync` function, this version takes an optional `options` object.
  2690. * If no `options` object is specified, it will default with the above values.
  2691. */
  2692. export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number;
  2693. /**
  2694. * Asynchronously reads the entire contents of a file.
  2695. *
  2696. * ```js
  2697. * import { readFile } from 'node:fs';
  2698. *
  2699. * readFile('/etc/passwd', (err, data) => {
  2700. * if (err) throw err;
  2701. * console.log(data);
  2702. * });
  2703. * ```
  2704. *
  2705. * The callback is passed two arguments `(err, data)`, where `data` is the
  2706. * contents of the file.
  2707. *
  2708. * If no encoding is specified, then the raw buffer is returned.
  2709. *
  2710. * If `options` is a string, then it specifies the encoding:
  2711. *
  2712. * ```js
  2713. * import { readFile } from 'node:fs';
  2714. *
  2715. * readFile('/etc/passwd', 'utf8', callback);
  2716. * ```
  2717. *
  2718. * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an
  2719. * error will be returned. On FreeBSD, a representation of the directory's contents
  2720. * will be returned.
  2721. *
  2722. * ```js
  2723. * import { readFile } from 'node:fs';
  2724. *
  2725. * // macOS, Linux, and Windows
  2726. * readFile('<directory>', (err, data) => {
  2727. * // => [Error: EISDIR: illegal operation on a directory, read <directory>]
  2728. * });
  2729. *
  2730. * // FreeBSD
  2731. * readFile('<directory>', (err, data) => {
  2732. * // => null, <data>
  2733. * });
  2734. * ```
  2735. *
  2736. * It is possible to abort an ongoing request using an `AbortSignal`. If a
  2737. * request is aborted the callback is called with an `AbortError`:
  2738. *
  2739. * ```js
  2740. * import { readFile } from 'node:fs';
  2741. *
  2742. * const controller = new AbortController();
  2743. * const signal = controller.signal;
  2744. * readFile(fileInfo[0].name, { signal }, (err, buf) => {
  2745. * // ...
  2746. * });
  2747. * // When you want to abort the request
  2748. * controller.abort();
  2749. * ```
  2750. *
  2751. * The `fs.readFile()` function buffers the entire file. To minimize memory costs,
  2752. * when possible prefer streaming via `fs.createReadStream()`.
  2753. *
  2754. * Aborting an ongoing request does not abort individual operating
  2755. * system requests but rather the internal buffering `fs.readFile` performs.
  2756. * @since v0.1.29
  2757. * @param path filename or file descriptor
  2758. */
  2759. export function readFile(
  2760. path: PathOrFileDescriptor,
  2761. options:
  2762. | ({
  2763. encoding?: null | undefined;
  2764. flag?: string | undefined;
  2765. } & Abortable)
  2766. | undefined
  2767. | null,
  2768. callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void,
  2769. ): void;
  2770. /**
  2771. * Asynchronously reads the entire contents of a file.
  2772. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2773. * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
  2774. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag.
  2775. * If a flag is not provided, it defaults to `'r'`.
  2776. */
  2777. export function readFile(
  2778. path: PathOrFileDescriptor,
  2779. options:
  2780. | ({
  2781. encoding: BufferEncoding;
  2782. flag?: string | undefined;
  2783. } & Abortable)
  2784. | BufferEncoding,
  2785. callback: (err: NodeJS.ErrnoException | null, data: string) => void,
  2786. ): void;
  2787. /**
  2788. * Asynchronously reads the entire contents of a file.
  2789. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2790. * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
  2791. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag.
  2792. * If a flag is not provided, it defaults to `'r'`.
  2793. */
  2794. export function readFile(
  2795. path: PathOrFileDescriptor,
  2796. options:
  2797. | (ObjectEncodingOptions & {
  2798. flag?: string | undefined;
  2799. } & Abortable)
  2800. | BufferEncoding
  2801. | undefined
  2802. | null,
  2803. callback: (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void,
  2804. ): void;
  2805. /**
  2806. * Asynchronously reads the entire contents of a file.
  2807. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2808. * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
  2809. */
  2810. export function readFile(
  2811. path: PathOrFileDescriptor,
  2812. callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void,
  2813. ): void;
  2814. export namespace readFile {
  2815. /**
  2816. * Asynchronously reads the entire contents of a file.
  2817. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2818. * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
  2819. * @param options An object that may contain an optional flag.
  2820. * If a flag is not provided, it defaults to `'r'`.
  2821. */
  2822. function __promisify__(
  2823. path: PathOrFileDescriptor,
  2824. options?: {
  2825. encoding?: null | undefined;
  2826. flag?: string | undefined;
  2827. } | null,
  2828. ): Promise<NonSharedBuffer>;
  2829. /**
  2830. * Asynchronously reads the entire contents of a file.
  2831. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2832. * URL support is _experimental_.
  2833. * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
  2834. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag.
  2835. * If a flag is not provided, it defaults to `'r'`.
  2836. */
  2837. function __promisify__(
  2838. path: PathOrFileDescriptor,
  2839. options:
  2840. | {
  2841. encoding: BufferEncoding;
  2842. flag?: string | undefined;
  2843. }
  2844. | BufferEncoding,
  2845. ): Promise<string>;
  2846. /**
  2847. * Asynchronously reads the entire contents of a file.
  2848. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2849. * URL support is _experimental_.
  2850. * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
  2851. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag.
  2852. * If a flag is not provided, it defaults to `'r'`.
  2853. */
  2854. function __promisify__(
  2855. path: PathOrFileDescriptor,
  2856. options?:
  2857. | (ObjectEncodingOptions & {
  2858. flag?: string | undefined;
  2859. })
  2860. | BufferEncoding
  2861. | null,
  2862. ): Promise<string | NonSharedBuffer>;
  2863. }
  2864. /**
  2865. * Returns the contents of the `path`.
  2866. *
  2867. * For detailed information, see the documentation of the asynchronous version of
  2868. * this API: {@link readFile}.
  2869. *
  2870. * If the `encoding` option is specified then this function returns a
  2871. * string. Otherwise it returns a buffer.
  2872. *
  2873. * Similar to {@link readFile}, when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific.
  2874. *
  2875. * ```js
  2876. * import { readFileSync } from 'node:fs';
  2877. *
  2878. * // macOS, Linux, and Windows
  2879. * readFileSync('<directory>');
  2880. * // => [Error: EISDIR: illegal operation on a directory, read <directory>]
  2881. *
  2882. * // FreeBSD
  2883. * readFileSync('<directory>'); // => <data>
  2884. * ```
  2885. * @since v0.1.8
  2886. * @param path filename or file descriptor
  2887. */
  2888. export function readFileSync(
  2889. path: PathOrFileDescriptor,
  2890. options?: {
  2891. encoding?: null | undefined;
  2892. flag?: string | undefined;
  2893. } | null,
  2894. ): NonSharedBuffer;
  2895. /**
  2896. * Synchronously reads the entire contents of a file.
  2897. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2898. * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
  2899. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag.
  2900. * If a flag is not provided, it defaults to `'r'`.
  2901. */
  2902. export function readFileSync(
  2903. path: PathOrFileDescriptor,
  2904. options:
  2905. | {
  2906. encoding: BufferEncoding;
  2907. flag?: string | undefined;
  2908. }
  2909. | BufferEncoding,
  2910. ): string;
  2911. /**
  2912. * Synchronously reads the entire contents of a file.
  2913. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  2914. * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
  2915. * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag.
  2916. * If a flag is not provided, it defaults to `'r'`.
  2917. */
  2918. export function readFileSync(
  2919. path: PathOrFileDescriptor,
  2920. options?:
  2921. | (ObjectEncodingOptions & {
  2922. flag?: string | undefined;
  2923. })
  2924. | BufferEncoding
  2925. | null,
  2926. ): string | NonSharedBuffer;
  2927. export type WriteFileOptions =
  2928. | (
  2929. & ObjectEncodingOptions
  2930. & Abortable
  2931. & {
  2932. mode?: Mode | undefined;
  2933. flag?: string | undefined;
  2934. flush?: boolean | undefined;
  2935. }
  2936. )
  2937. | BufferEncoding
  2938. | null;
  2939. /**
  2940. * When `file` is a filename, asynchronously writes data to the file, replacing the
  2941. * file if it already exists. `data` can be a string or a buffer.
  2942. *
  2943. * When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using
  2944. * a file descriptor.
  2945. *
  2946. * The `encoding` option is ignored if `data` is a buffer.
  2947. *
  2948. * The `mode` option only affects the newly created file. See {@link open} for more details.
  2949. *
  2950. * ```js
  2951. * import { writeFile } from 'node:fs';
  2952. * import { Buffer } from 'node:buffer';
  2953. *
  2954. * const data = new Uint8Array(Buffer.from('Hello Node.js'));
  2955. * writeFile('message.txt', data, (err) => {
  2956. * if (err) throw err;
  2957. * console.log('The file has been saved!');
  2958. * });
  2959. * ```
  2960. *
  2961. * If `options` is a string, then it specifies the encoding:
  2962. *
  2963. * ```js
  2964. * import { writeFile } from 'node:fs';
  2965. *
  2966. * writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
  2967. * ```
  2968. *
  2969. * It is unsafe to use `fs.writeFile()` multiple times on the same file without
  2970. * waiting for the callback. For this scenario, {@link createWriteStream} is
  2971. * recommended.
  2972. *
  2973. * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that
  2974. * performs multiple `write` calls internally to write the buffer passed to it.
  2975. * For performance sensitive code consider using {@link createWriteStream}.
  2976. *
  2977. * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`.
  2978. * Cancelation is "best effort", and some amount of data is likely still
  2979. * to be written.
  2980. *
  2981. * ```js
  2982. * import { writeFile } from 'node:fs';
  2983. * import { Buffer } from 'node:buffer';
  2984. *
  2985. * const controller = new AbortController();
  2986. * const { signal } = controller;
  2987. * const data = new Uint8Array(Buffer.from('Hello Node.js'));
  2988. * writeFile('message.txt', data, { signal }, (err) => {
  2989. * // When a request is aborted - the callback is called with an AbortError
  2990. * });
  2991. * // When the request should be aborted
  2992. * controller.abort();
  2993. * ```
  2994. *
  2995. * Aborting an ongoing request does not abort individual operating
  2996. * system requests but rather the internal buffering `fs.writeFile` performs.
  2997. * @since v0.1.29
  2998. * @param file filename or file descriptor
  2999. */
  3000. export function writeFile(
  3001. file: PathOrFileDescriptor,
  3002. data: string | NodeJS.ArrayBufferView,
  3003. options: WriteFileOptions,
  3004. callback: NoParamCallback,
  3005. ): void;
  3006. /**
  3007. * Asynchronously writes data to a file, replacing the file if it already exists.
  3008. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  3009. * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
  3010. * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
  3011. */
  3012. export function writeFile(
  3013. path: PathOrFileDescriptor,
  3014. data: string | NodeJS.ArrayBufferView,
  3015. callback: NoParamCallback,
  3016. ): void;
  3017. export namespace writeFile {
  3018. /**
  3019. * Asynchronously writes data to a file, replacing the file if it already exists.
  3020. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
  3021. * URL support is _experimental_.
  3022. * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
  3023. * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
  3024. * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag.
  3025. * If `encoding` is not supplied, the default of `'utf8'` is used.
  3026. * If `mode` is not supplied, the default of `0o666` is used.
  3027. * If `mode` is a string, it is parsed as an octal integer.
  3028. * If `flag` is not supplied, the default of `'w'` is used.
  3029. */
  3030. function __promisify__(
  3031. path: PathOrFileDescriptor,
  3032. data: string | NodeJS.ArrayBufferView,
  3033. options?: WriteFileOptions,
  3034. ): Promise<void>;
  3035. }
  3036. /**
  3037. * Returns `undefined`.
  3038. *
  3039. * The `mode` option only affects the newly created file. See {@link open} for more details.
  3040. *
  3041. * For detailed information, see the documentation of the asynchronous version of
  3042. * this API: {@link writeFile}.
  3043. * @since v0.1.29
  3044. * @param file filename or file descriptor
  3045. */
  3046. export function writeFileSync(
  3047. file: PathOrFileDescriptor,
  3048. data: string | NodeJS.ArrayBufferView,
  3049. options?: WriteFileOptions,
  3050. ): void;
  3051. /**
  3052. * Asynchronously append data to a file, creating the file if it does not yet
  3053. * exist. `data` can be a string or a `Buffer`.
  3054. *
  3055. * The `mode` option only affects the newly created file. See {@link open} for more details.
  3056. *
  3057. * ```js
  3058. * import { appendFile } from 'node:fs';
  3059. *
  3060. * appendFile('message.txt', 'data to append', (err) => {
  3061. * if (err) throw err;
  3062. * console.log('The "data to append" was appended to file!');
  3063. * });
  3064. * ```
  3065. *
  3066. * If `options` is a string, then it specifies the encoding:
  3067. *
  3068. * ```js
  3069. * import { appendFile } from 'node:fs';
  3070. *
  3071. * appendFile('message.txt', 'data to append', 'utf8', callback);
  3072. * ```
  3073. *
  3074. * The `path` may be specified as a numeric file descriptor that has been opened
  3075. * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will
  3076. * not be closed automatically.
  3077. *
  3078. * ```js
  3079. * import { open, close, appendFile } from 'node:fs';
  3080. *
  3081. * function closeFd(fd) {
  3082. * close(fd, (err) => {
  3083. * if (err) throw err;
  3084. * });
  3085. * }
  3086. *
  3087. * open('message.txt', 'a', (err, fd) => {
  3088. * if (err) throw err;
  3089. *
  3090. * try {
  3091. * appendFile(fd, 'data to append', 'utf8', (err) => {
  3092. * closeFd(fd);
  3093. * if (err) throw err;
  3094. * });
  3095. * } catch (err) {
  3096. * closeFd(fd);
  3097. * throw err;
  3098. * }
  3099. * });
  3100. * ```
  3101. * @since v0.6.7
  3102. * @param path filename or file descriptor
  3103. */
  3104. export function appendFile(
  3105. path: PathOrFileDescriptor,
  3106. data: string | Uint8Array,
  3107. options: WriteFileOptions,
  3108. callback: NoParamCallback,
  3109. ): void;
  3110. /**
  3111. * Asynchronously append data to a file, creating the file if it does not exist.
  3112. * @param file A path to a file. If a URL is provided, it must use the `file:` protocol.
  3113. * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
  3114. * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
  3115. */
  3116. export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void;
  3117. export namespace appendFile {
  3118. /**
  3119. * Asynchronously append data to a file, creating the file if it does not exist.
  3120. * @param file A path to a file. If a URL is provided, it must use the `file:` protocol.
  3121. * URL support is _experimental_.
  3122. * If a file descriptor is provided, the underlying file will _not_ be closed automatically.
  3123. * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
  3124. * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag.
  3125. * If `encoding` is not supplied, the default of `'utf8'` is used.
  3126. * If `mode` is not supplied, the default of `0o666` is used.
  3127. * If `mode` is a string, it is parsed as an octal integer.
  3128. * If `flag` is not supplied, the default of `'a'` is used.
  3129. */
  3130. function __promisify__(
  3131. file: PathOrFileDescriptor,
  3132. data: string | Uint8Array,
  3133. options?: WriteFileOptions,
  3134. ): Promise<void>;
  3135. }
  3136. /**
  3137. * Synchronously append data to a file, creating the file if it does not yet
  3138. * exist. `data` can be a string or a `Buffer`.
  3139. *
  3140. * The `mode` option only affects the newly created file. See {@link open} for more details.
  3141. *
  3142. * ```js
  3143. * import { appendFileSync } from 'node:fs';
  3144. *
  3145. * try {
  3146. * appendFileSync('message.txt', 'data to append');
  3147. * console.log('The "data to append" was appended to file!');
  3148. * } catch (err) {
  3149. * // Handle the error
  3150. * }
  3151. * ```
  3152. *
  3153. * If `options` is a string, then it specifies the encoding:
  3154. *
  3155. * ```js
  3156. * import { appendFileSync } from 'node:fs';
  3157. *
  3158. * appendFileSync('message.txt', 'data to append', 'utf8');
  3159. * ```
  3160. *
  3161. * The `path` may be specified as a numeric file descriptor that has been opened
  3162. * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will
  3163. * not be closed automatically.
  3164. *
  3165. * ```js
  3166. * import { openSync, closeSync, appendFileSync } from 'node:fs';
  3167. *
  3168. * let fd;
  3169. *
  3170. * try {
  3171. * fd = openSync('message.txt', 'a');
  3172. * appendFileSync(fd, 'data to append', 'utf8');
  3173. * } catch (err) {
  3174. * // Handle the error
  3175. * } finally {
  3176. * if (fd !== undefined)
  3177. * closeSync(fd);
  3178. * }
  3179. * ```
  3180. * @since v0.6.7
  3181. * @param path filename or file descriptor
  3182. */
  3183. export function appendFileSync(
  3184. path: PathOrFileDescriptor,
  3185. data: string | Uint8Array,
  3186. options?: WriteFileOptions,
  3187. ): void;
  3188. /**
  3189. * Watch for changes on `filename`. The callback `listener` will be called each
  3190. * time the file is accessed.
  3191. *
  3192. * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates
  3193. * whether the process should continue to run as long as files are being watched.
  3194. * The `options` object may specify an `interval` property indicating how often the
  3195. * target should be polled in milliseconds.
  3196. *
  3197. * The `listener` gets two arguments the current stat object and the previous
  3198. * stat object:
  3199. *
  3200. * ```js
  3201. * import { watchFile } from 'node:fs';
  3202. *
  3203. * watchFile('message.text', (curr, prev) => {
  3204. * console.log(`the current mtime is: ${curr.mtime}`);
  3205. * console.log(`the previous mtime was: ${prev.mtime}`);
  3206. * });
  3207. * ```
  3208. *
  3209. * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`,
  3210. * the numeric values in these objects are specified as `BigInt`s.
  3211. *
  3212. * To be notified when the file was modified, not just accessed, it is necessary
  3213. * to compare `curr.mtimeMs` and `prev.mtimeMs`.
  3214. *
  3215. * When an `fs.watchFile` operation results in an `ENOENT` error, it
  3216. * will invoke the listener once, with all the fields zeroed (or, for dates, the
  3217. * Unix Epoch). If the file is created later on, the listener will be called
  3218. * again, with the latest stat objects. This is a change in functionality since
  3219. * v0.10.
  3220. *
  3221. * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible.
  3222. *
  3223. * When a file being watched by `fs.watchFile()` disappears and reappears,
  3224. * then the contents of `previous` in the second callback event (the file's
  3225. * reappearance) will be the same as the contents of `previous` in the first
  3226. * callback event (its disappearance).
  3227. *
  3228. * This happens when:
  3229. *
  3230. * * the file is deleted, followed by a restore
  3231. * * the file is renamed and then renamed a second time back to its original name
  3232. * @since v0.1.31
  3233. */
  3234. export interface WatchFileOptions {
  3235. bigint?: boolean | undefined;
  3236. persistent?: boolean | undefined;
  3237. interval?: number | undefined;
  3238. }
  3239. /**
  3240. * Watch for changes on `filename`. The callback `listener` will be called each
  3241. * time the file is accessed.
  3242. *
  3243. * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates
  3244. * whether the process should continue to run as long as files are being watched.
  3245. * The `options` object may specify an `interval` property indicating how often the
  3246. * target should be polled in milliseconds.
  3247. *
  3248. * The `listener` gets two arguments the current stat object and the previous
  3249. * stat object:
  3250. *
  3251. * ```js
  3252. * import { watchFile } from 'node:fs';
  3253. *
  3254. * watchFile('message.text', (curr, prev) => {
  3255. * console.log(`the current mtime is: ${curr.mtime}`);
  3256. * console.log(`the previous mtime was: ${prev.mtime}`);
  3257. * });
  3258. * ```
  3259. *
  3260. * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`,
  3261. * the numeric values in these objects are specified as `BigInt`s.
  3262. *
  3263. * To be notified when the file was modified, not just accessed, it is necessary
  3264. * to compare `curr.mtimeMs` and `prev.mtimeMs`.
  3265. *
  3266. * When an `fs.watchFile` operation results in an `ENOENT` error, it
  3267. * will invoke the listener once, with all the fields zeroed (or, for dates, the
  3268. * Unix Epoch). If the file is created later on, the listener will be called
  3269. * again, with the latest stat objects. This is a change in functionality since
  3270. * v0.10.
  3271. *
  3272. * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible.
  3273. *
  3274. * When a file being watched by `fs.watchFile()` disappears and reappears,
  3275. * then the contents of `previous` in the second callback event (the file's
  3276. * reappearance) will be the same as the contents of `previous` in the first
  3277. * callback event (its disappearance).
  3278. *
  3279. * This happens when:
  3280. *
  3281. * * the file is deleted, followed by a restore
  3282. * * the file is renamed and then renamed a second time back to its original name
  3283. * @since v0.1.31
  3284. */
  3285. export function watchFile(
  3286. filename: PathLike,
  3287. options:
  3288. | (WatchFileOptions & {
  3289. bigint?: false | undefined;
  3290. })
  3291. | undefined,
  3292. listener: StatsListener,
  3293. ): StatWatcher;
  3294. export function watchFile(
  3295. filename: PathLike,
  3296. options:
  3297. | (WatchFileOptions & {
  3298. bigint: true;
  3299. })
  3300. | undefined,
  3301. listener: BigIntStatsListener,
  3302. ): StatWatcher;
  3303. /**
  3304. * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed.
  3305. * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
  3306. */
  3307. export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher;
  3308. /**
  3309. * Stop watching for changes on `filename`. If `listener` is specified, only that
  3310. * particular listener is removed. Otherwise, _all_ listeners are removed,
  3311. * effectively stopping watching of `filename`.
  3312. *
  3313. * Calling `fs.unwatchFile()` with a filename that is not being watched is a
  3314. * no-op, not an error.
  3315. *
  3316. * Using {@link watch} is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible.
  3317. * @since v0.1.31
  3318. * @param listener Optional, a listener previously attached using `fs.watchFile()`
  3319. */
  3320. export function unwatchFile(filename: PathLike, listener?: StatsListener): void;
  3321. export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void;
  3322. export interface WatchOptions extends Abortable {
  3323. encoding?: BufferEncoding | "buffer" | undefined;
  3324. persistent?: boolean | undefined;
  3325. recursive?: boolean | undefined;
  3326. }
  3327. export type WatchEventType = "rename" | "change";
  3328. export type WatchListener<T> = (event: WatchEventType, filename: T | null) => void;
  3329. export type StatsListener = (curr: Stats, prev: Stats) => void;
  3330. export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void;
  3331. /**
  3332. * Watch for changes on `filename`, where `filename` is either a file or a
  3333. * directory.
  3334. *
  3335. * The second argument is optional. If `options` is provided as a string, it
  3336. * specifies the `encoding`. Otherwise `options` should be passed as an object.
  3337. *
  3338. * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file
  3339. * which triggered the event.
  3340. *
  3341. * On most platforms, `'rename'` is emitted whenever a filename appears or
  3342. * disappears in the directory.
  3343. *
  3344. * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of `eventType`.
  3345. *
  3346. * If a `signal` is passed, aborting the corresponding AbortController will close
  3347. * the returned `fs.FSWatcher`.
  3348. * @since v0.5.10
  3349. * @param listener
  3350. */
  3351. export function watch(
  3352. filename: PathLike,
  3353. options:
  3354. | (WatchOptions & {
  3355. encoding: "buffer";
  3356. })
  3357. | "buffer",
  3358. listener?: WatchListener<Buffer>,
  3359. ): FSWatcher;
  3360. /**
  3361. * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
  3362. * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
  3363. * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
  3364. * If `encoding` is not supplied, the default of `'utf8'` is used.
  3365. * If `persistent` is not supplied, the default of `true` is used.
  3366. * If `recursive` is not supplied, the default of `false` is used.
  3367. */
  3368. export function watch(
  3369. filename: PathLike,
  3370. options?: WatchOptions | BufferEncoding | null,
  3371. listener?: WatchListener<string>,
  3372. ): FSWatcher;
  3373. /**
  3374. * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
  3375. * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
  3376. * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
  3377. * If `encoding` is not supplied, the default of `'utf8'` is used.
  3378. * If `persistent` is not supplied, the default of `true` is used.
  3379. * If `recursive` is not supplied, the default of `false` is used.
  3380. */
  3381. export function watch(
  3382. filename: PathLike,
  3383. options: WatchOptions | string,
  3384. listener?: WatchListener<string | Buffer>,
  3385. ): FSWatcher;
  3386. /**
  3387. * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
  3388. * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
  3389. */
  3390. export function watch(filename: PathLike, listener?: WatchListener<string>): FSWatcher;
  3391. /**
  3392. * Test whether or not the given path exists by checking with the file system.
  3393. * Then call the `callback` argument with either true or false:
  3394. *
  3395. * ```js
  3396. * import { exists } from 'node:fs';
  3397. *
  3398. * exists('/etc/passwd', (e) => {
  3399. * console.log(e ? 'it exists' : 'no passwd!');
  3400. * });
  3401. * ```
  3402. *
  3403. * **The parameters for this callback are not consistent with other Node.js**
  3404. * **callbacks.** Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback
  3405. * has only one boolean parameter. This is one reason `fs.access()` is recommended
  3406. * instead of `fs.exists()`.
  3407. *
  3408. * Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing
  3409. * so introduces a race condition, since other processes may change the file's
  3410. * state between the two calls. Instead, user code should open/read/write the
  3411. * file directly and handle the error raised if the file does not exist.
  3412. *
  3413. * **write (NOT RECOMMENDED)**
  3414. *
  3415. * ```js
  3416. * import { exists, open, close } from 'node:fs';
  3417. *
  3418. * exists('myfile', (e) => {
  3419. * if (e) {
  3420. * console.error('myfile already exists');
  3421. * } else {
  3422. * open('myfile', 'wx', (err, fd) => {
  3423. * if (err) throw err;
  3424. *
  3425. * try {
  3426. * writeMyData(fd);
  3427. * } finally {
  3428. * close(fd, (err) => {
  3429. * if (err) throw err;
  3430. * });
  3431. * }
  3432. * });
  3433. * }
  3434. * });
  3435. * ```
  3436. *
  3437. * **write (RECOMMENDED)**
  3438. *
  3439. * ```js
  3440. * import { open, close } from 'node:fs';
  3441. * open('myfile', 'wx', (err, fd) => {
  3442. * if (err) {
  3443. * if (err.code === 'EEXIST') {
  3444. * console.error('myfile already exists');
  3445. * return;
  3446. * }
  3447. *
  3448. * throw err;
  3449. * }
  3450. *
  3451. * try {
  3452. * writeMyData(fd);
  3453. * } finally {
  3454. * close(fd, (err) => {
  3455. * if (err) throw err;
  3456. * });
  3457. * }
  3458. * });
  3459. * ```
  3460. *
  3461. * **read (NOT RECOMMENDED)**
  3462. *
  3463. * ```js
  3464. * import { open, close, exists } from 'node:fs';
  3465. *
  3466. * exists('myfile', (e) => {
  3467. * if (e) {
  3468. * open('myfile', 'r', (err, fd) => {
  3469. * if (err) throw err;
  3470. *
  3471. * try {
  3472. * readMyData(fd);
  3473. * } finally {
  3474. * close(fd, (err) => {
  3475. * if (err) throw err;
  3476. * });
  3477. * }
  3478. * });
  3479. * } else {
  3480. * console.error('myfile does not exist');
  3481. * }
  3482. * });
  3483. * ```
  3484. *
  3485. * **read (RECOMMENDED)**
  3486. *
  3487. * ```js
  3488. * import { open, close } from 'node:fs';
  3489. *
  3490. * open('myfile', 'r', (err, fd) => {
  3491. * if (err) {
  3492. * if (err.code === 'ENOENT') {
  3493. * console.error('myfile does not exist');
  3494. * return;
  3495. * }
  3496. *
  3497. * throw err;
  3498. * }
  3499. *
  3500. * try {
  3501. * readMyData(fd);
  3502. * } finally {
  3503. * close(fd, (err) => {
  3504. * if (err) throw err;
  3505. * });
  3506. * }
  3507. * });
  3508. * ```
  3509. *
  3510. * The "not recommended" examples above check for existence and then use the
  3511. * file; the "recommended" examples are better because they use the file directly
  3512. * and handle the error, if any.
  3513. *
  3514. * In general, check for the existence of a file only if the file won't be
  3515. * used directly, for example when its existence is a signal from another
  3516. * process.
  3517. * @since v0.0.2
  3518. * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead.
  3519. */
  3520. export function exists(path: PathLike, callback: (exists: boolean) => void): void;
  3521. /** @deprecated */
  3522. export namespace exists {
  3523. /**
  3524. * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
  3525. * URL support is _experimental_.
  3526. */
  3527. function __promisify__(path: PathLike): Promise<boolean>;
  3528. }
  3529. /**
  3530. * Returns `true` if the path exists, `false` otherwise.
  3531. *
  3532. * For detailed information, see the documentation of the asynchronous version of
  3533. * this API: {@link exists}.
  3534. *
  3535. * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other
  3536. * Node.js callbacks. `fs.existsSync()` does not use a callback.
  3537. *
  3538. * ```js
  3539. * import { existsSync } from 'node:fs';
  3540. *
  3541. * if (existsSync('/etc/passwd'))
  3542. * console.log('The path exists.');
  3543. * ```
  3544. * @since v0.1.21
  3545. */
  3546. export function existsSync(path: PathLike): boolean;
  3547. export namespace constants {
  3548. // File Access Constants
  3549. /** Constant for fs.access(). File is visible to the calling process. */
  3550. const F_OK: number;
  3551. /** Constant for fs.access(). File can be read by the calling process. */
  3552. const R_OK: number;
  3553. /** Constant for fs.access(). File can be written by the calling process. */
  3554. const W_OK: number;
  3555. /** Constant for fs.access(). File can be executed by the calling process. */
  3556. const X_OK: number;
  3557. // File Copy Constants
  3558. /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */
  3559. const COPYFILE_EXCL: number;
  3560. /**
  3561. * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink.
  3562. * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used.
  3563. */
  3564. const COPYFILE_FICLONE: number;
  3565. /**
  3566. * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink.
  3567. * If the underlying platform does not support copy-on-write, then the operation will fail with an error.
  3568. */
  3569. const COPYFILE_FICLONE_FORCE: number;
  3570. // File Open Constants
  3571. /** Constant for fs.open(). Flag indicating to open a file for read-only access. */
  3572. const O_RDONLY: number;
  3573. /** Constant for fs.open(). Flag indicating to open a file for write-only access. */
  3574. const O_WRONLY: number;
  3575. /** Constant for fs.open(). Flag indicating to open a file for read-write access. */
  3576. const O_RDWR: number;
  3577. /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */
  3578. const O_CREAT: number;
  3579. /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */
  3580. const O_EXCL: number;
  3581. /**
  3582. * Constant for fs.open(). Flag indicating that if path identifies a terminal device,
  3583. * opening the path shall not cause that terminal to become the controlling terminal for the process
  3584. * (if the process does not already have one).
  3585. */
  3586. const O_NOCTTY: number;
  3587. /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */
  3588. const O_TRUNC: number;
  3589. /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */
  3590. const O_APPEND: number;
  3591. /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */
  3592. const O_DIRECTORY: number;
  3593. /**
  3594. * constant for fs.open().
  3595. * Flag indicating reading accesses to the file system will no longer result in
  3596. * an update to the atime information associated with the file.
  3597. * This flag is available on Linux operating systems only.
  3598. */
  3599. const O_NOATIME: number;
  3600. /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */
  3601. const O_NOFOLLOW: number;
  3602. /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */
  3603. const O_SYNC: number;
  3604. /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */
  3605. const O_DSYNC: number;
  3606. /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */
  3607. const O_SYMLINK: number;
  3608. /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */
  3609. const O_DIRECT: number;
  3610. /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */
  3611. const O_NONBLOCK: number;
  3612. // File Type Constants
  3613. /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */
  3614. const S_IFMT: number;
  3615. /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */
  3616. const S_IFREG: number;
  3617. /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */
  3618. const S_IFDIR: number;
  3619. /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */
  3620. const S_IFCHR: number;
  3621. /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */
  3622. const S_IFBLK: number;
  3623. /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */
  3624. const S_IFIFO: number;
  3625. /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */
  3626. const S_IFLNK: number;
  3627. /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */
  3628. const S_IFSOCK: number;
  3629. // File Mode Constants
  3630. /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */
  3631. const S_IRWXU: number;
  3632. /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */
  3633. const S_IRUSR: number;
  3634. /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */
  3635. const S_IWUSR: number;
  3636. /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */
  3637. const S_IXUSR: number;
  3638. /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */
  3639. const S_IRWXG: number;
  3640. /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */
  3641. const S_IRGRP: number;
  3642. /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */
  3643. const S_IWGRP: number;
  3644. /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */
  3645. const S_IXGRP: number;
  3646. /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */
  3647. const S_IRWXO: number;
  3648. /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */
  3649. const S_IROTH: number;
  3650. /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */
  3651. const S_IWOTH: number;
  3652. /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */
  3653. const S_IXOTH: number;
  3654. /**
  3655. * When set, a memory file mapping is used to access the file. This flag
  3656. * is available on Windows operating systems only. On other operating systems,
  3657. * this flag is ignored.
  3658. */
  3659. const UV_FS_O_FILEMAP: number;
  3660. }
  3661. /**
  3662. * Tests a user's permissions for the file or directory specified by `path`.
  3663. * The `mode` argument is an optional integer that specifies the accessibility
  3664. * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK`
  3665. * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for
  3666. * possible values of `mode`.
  3667. *
  3668. * The final argument, `callback`, is a callback function that is invoked with
  3669. * a possible error argument. If any of the accessibility checks fail, the error
  3670. * argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable.
  3671. *
  3672. * ```js
  3673. * import { access, constants } from 'node:fs';
  3674. *
  3675. * const file = 'package.json';
  3676. *
  3677. * // Check if the file exists in the current directory.
  3678. * access(file, constants.F_OK, (err) => {
  3679. * console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
  3680. * });
  3681. *
  3682. * // Check if the file is readable.
  3683. * access(file, constants.R_OK, (err) => {
  3684. * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
  3685. * });
  3686. *
  3687. * // Check if the file is writable.
  3688. * access(file, constants.W_OK, (err) => {
  3689. * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
  3690. * });
  3691. *
  3692. * // Check if the file is readable and writable.
  3693. * access(file, constants.R_OK | constants.W_OK, (err) => {
  3694. * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`);
  3695. * });
  3696. * ```
  3697. *
  3698. * Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing
  3699. * so introduces a race condition, since other processes may change the file's
  3700. * state between the two calls. Instead, user code should open/read/write the
  3701. * file directly and handle the error raised if the file is not accessible.
  3702. *
  3703. * **write (NOT RECOMMENDED)**
  3704. *
  3705. * ```js
  3706. * import { access, open, close } from 'node:fs';
  3707. *
  3708. * access('myfile', (err) => {
  3709. * if (!err) {
  3710. * console.error('myfile already exists');
  3711. * return;
  3712. * }
  3713. *
  3714. * open('myfile', 'wx', (err, fd) => {
  3715. * if (err) throw err;
  3716. *
  3717. * try {
  3718. * writeMyData(fd);
  3719. * } finally {
  3720. * close(fd, (err) => {
  3721. * if (err) throw err;
  3722. * });
  3723. * }
  3724. * });
  3725. * });
  3726. * ```
  3727. *
  3728. * **write (RECOMMENDED)**
  3729. *
  3730. * ```js
  3731. * import { open, close } from 'node:fs';
  3732. *
  3733. * open('myfile', 'wx', (err, fd) => {
  3734. * if (err) {
  3735. * if (err.code === 'EEXIST') {
  3736. * console.error('myfile already exists');
  3737. * return;
  3738. * }
  3739. *
  3740. * throw err;
  3741. * }
  3742. *
  3743. * try {
  3744. * writeMyData(fd);
  3745. * } finally {
  3746. * close(fd, (err) => {
  3747. * if (err) throw err;
  3748. * });
  3749. * }
  3750. * });
  3751. * ```
  3752. *
  3753. * **read (NOT RECOMMENDED)**
  3754. *
  3755. * ```js
  3756. * import { access, open, close } from 'node:fs';
  3757. * access('myfile', (err) => {
  3758. * if (err) {
  3759. * if (err.code === 'ENOENT') {
  3760. * console.error('myfile does not exist');
  3761. * return;
  3762. * }
  3763. *
  3764. * throw err;
  3765. * }
  3766. *
  3767. * open('myfile', 'r', (err, fd) => {
  3768. * if (err) throw err;
  3769. *
  3770. * try {
  3771. * readMyData(fd);
  3772. * } finally {
  3773. * close(fd, (err) => {
  3774. * if (err) throw err;
  3775. * });
  3776. * }
  3777. * });
  3778. * });
  3779. * ```
  3780. *
  3781. * **read (RECOMMENDED)**
  3782. *
  3783. * ```js
  3784. * import { open, close } from 'node:fs';
  3785. *
  3786. * open('myfile', 'r', (err, fd) => {
  3787. * if (err) {
  3788. * if (err.code === 'ENOENT') {
  3789. * console.error('myfile does not exist');
  3790. * return;
  3791. * }
  3792. *
  3793. * throw err;
  3794. * }
  3795. *
  3796. * try {
  3797. * readMyData(fd);
  3798. * } finally {
  3799. * close(fd, (err) => {
  3800. * if (err) throw err;
  3801. * });
  3802. * }
  3803. * });
  3804. * ```
  3805. *
  3806. * The "not recommended" examples above check for accessibility and then use the
  3807. * file; the "recommended" examples are better because they use the file directly
  3808. * and handle the error, if any.
  3809. *
  3810. * In general, check for the accessibility of a file only if the file will not be
  3811. * used directly, for example when its accessibility is a signal from another
  3812. * process.
  3813. *
  3814. * On Windows, access-control policies (ACLs) on a directory may limit access to
  3815. * a file or directory. The `fs.access()` function, however, does not check the
  3816. * ACL and therefore may report that a path is accessible even if the ACL restricts
  3817. * the user from reading or writing to it.
  3818. * @since v0.11.15
  3819. * @param [mode=fs.constants.F_OK]
  3820. */
  3821. export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void;
  3822. /**
  3823. * Asynchronously tests a user's permissions for the file specified by path.
  3824. * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
  3825. */
  3826. export function access(path: PathLike, callback: NoParamCallback): void;
  3827. export namespace access {
  3828. /**
  3829. * Asynchronously tests a user's permissions for the file specified by path.
  3830. * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
  3831. * URL support is _experimental_.
  3832. */
  3833. function __promisify__(path: PathLike, mode?: number): Promise<void>;
  3834. }
  3835. /**
  3836. * Synchronously tests a user's permissions for the file or directory specified
  3837. * by `path`. The `mode` argument is an optional integer that specifies the
  3838. * accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and
  3839. * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for
  3840. * possible values of `mode`.
  3841. *
  3842. * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise,
  3843. * the method will return `undefined`.
  3844. *
  3845. * ```js
  3846. * import { accessSync, constants } from 'node:fs';
  3847. *
  3848. * try {
  3849. * accessSync('etc/passwd', constants.R_OK | constants.W_OK);
  3850. * console.log('can read/write');
  3851. * } catch (err) {
  3852. * console.error('no access!');
  3853. * }
  3854. * ```
  3855. * @since v0.11.15
  3856. * @param [mode=fs.constants.F_OK]
  3857. */
  3858. export function accessSync(path: PathLike, mode?: number): void;
  3859. interface StreamOptions {
  3860. flags?: string | undefined;
  3861. encoding?: BufferEncoding | undefined;
  3862. fd?: number | promises.FileHandle | undefined;
  3863. mode?: number | undefined;
  3864. autoClose?: boolean | undefined;
  3865. emitClose?: boolean | undefined;
  3866. start?: number | undefined;
  3867. signal?: AbortSignal | null | undefined;
  3868. highWaterMark?: number | undefined;
  3869. }
  3870. interface FSImplementation {
  3871. open?: (...args: any[]) => any;
  3872. close?: (...args: any[]) => any;
  3873. }
  3874. interface CreateReadStreamFSImplementation extends FSImplementation {
  3875. read: (...args: any[]) => any;
  3876. }
  3877. interface CreateWriteStreamFSImplementation extends FSImplementation {
  3878. write: (...args: any[]) => any;
  3879. writev?: (...args: any[]) => any;
  3880. }
  3881. interface ReadStreamOptions extends StreamOptions {
  3882. fs?: CreateReadStreamFSImplementation | null | undefined;
  3883. end?: number | undefined;
  3884. }
  3885. interface WriteStreamOptions extends StreamOptions {
  3886. fs?: CreateWriteStreamFSImplementation | null | undefined;
  3887. flush?: boolean | undefined;
  3888. }
  3889. /**
  3890. * `options` can include `start` and `end` values to read a range of bytes from
  3891. * the file instead of the entire file. Both `start` and `end` are inclusive and
  3892. * start counting at 0, allowed values are in the
  3893. * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is
  3894. * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the
  3895. * current file position. The `encoding` can be any one of those accepted by `Buffer`.
  3896. *
  3897. * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use
  3898. * the specified file descriptor. This means that no `'open'` event will be
  3899. * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`.
  3900. *
  3901. * If `fd` points to a character device that only supports blocking reads
  3902. * (such as keyboard or sound card), read operations do not finish until data is
  3903. * available. This can prevent the process from exiting and the stream from
  3904. * closing naturally.
  3905. *
  3906. * By default, the stream will emit a `'close'` event after it has been
  3907. * destroyed. Set the `emitClose` option to `false` to change this behavior.
  3908. *
  3909. * By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option,
  3910. * an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is
  3911. * also required.
  3912. *
  3913. * ```js
  3914. * import { createReadStream } from 'node:fs';
  3915. *
  3916. * // Create a stream from some character device.
  3917. * const stream = createReadStream('/dev/input/event0');
  3918. * setTimeout(() => {
  3919. * stream.close(); // This may not close the stream.
  3920. * // Artificially marking end-of-stream, as if the underlying resource had
  3921. * // indicated end-of-file by itself, allows the stream to close.
  3922. * // This does not cancel pending read operations, and if there is such an
  3923. * // operation, the process may still not be able to exit successfully
  3924. * // until it finishes.
  3925. * stream.push(null);
  3926. * stream.read(0);
  3927. * }, 100);
  3928. * ```
  3929. *
  3930. * If `autoClose` is false, then the file descriptor won't be closed, even if
  3931. * there's an error. It is the application's responsibility to close it and make
  3932. * sure there's no file descriptor leak. If `autoClose` is set to true (default
  3933. * behavior), on `'error'` or `'end'` the file descriptor will be closed
  3934. * automatically.
  3935. *
  3936. * `mode` sets the file mode (permission and sticky bits), but only if the
  3937. * file was created.
  3938. *
  3939. * An example to read the last 10 bytes of a file which is 100 bytes long:
  3940. *
  3941. * ```js
  3942. * import { createReadStream } from 'node:fs';
  3943. *
  3944. * createReadStream('sample.txt', { start: 90, end: 99 });
  3945. * ```
  3946. *
  3947. * If `options` is a string, then it specifies the encoding.
  3948. * @since v0.1.31
  3949. */
  3950. export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream;
  3951. /**
  3952. * `options` may also include a `start` option to allow writing data at some
  3953. * position past the beginning of the file, allowed values are in the
  3954. * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than
  3955. * replacing it may require the `flags` option to be set to `r+` rather than the
  3956. * default `w`. The `encoding` can be any one of those accepted by `Buffer`.
  3957. *
  3958. * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false,
  3959. * then the file descriptor won't be closed, even if there's an error.
  3960. * It is the application's responsibility to close it and make sure there's no
  3961. * file descriptor leak.
  3962. *
  3963. * By default, the stream will emit a `'close'` event after it has been
  3964. * destroyed. Set the `emitClose` option to `false` to change this behavior.
  3965. *
  3966. * By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce
  3967. * performance as some optimizations (`_writev()`)
  3968. * will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override
  3969. * for `open` is also required. If `autoClose` is `true`, an override for `close` is also required.
  3970. *
  3971. * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be
  3972. * emitted. `fd` should be blocking; non-blocking `fd`s
  3973. * should be passed to `net.Socket`.
  3974. *
  3975. * If `options` is a string, then it specifies the encoding.
  3976. * @since v0.1.31
  3977. */
  3978. export function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream;
  3979. /**
  3980. * Forces all currently queued I/O operations associated with the file to the
  3981. * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other
  3982. * than a possible
  3983. * exception are given to the completion callback.
  3984. * @since v0.1.96
  3985. */
  3986. export function fdatasync(fd: number, callback: NoParamCallback): void;
  3987. export namespace fdatasync {
  3988. /**
  3989. * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device.
  3990. * @param fd A file descriptor.
  3991. */
  3992. function __promisify__(fd: number): Promise<void>;
  3993. }
  3994. /**
  3995. * Forces all currently queued I/O operations associated with the file to the
  3996. * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`.
  3997. * @since v0.1.96
  3998. */
  3999. export function fdatasyncSync(fd: number): void;
  4000. /**
  4001. * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it
  4002. * already exists. No arguments other than a possible exception are given to the
  4003. * callback function. Node.js makes no guarantees about the atomicity of the copy
  4004. * operation. If an error occurs after the destination file has been opened for
  4005. * writing, Node.js will attempt to remove the destination.
  4006. *
  4007. * `mode` is an optional integer that specifies the behavior
  4008. * of the copy operation. It is possible to create a mask consisting of the bitwise
  4009. * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`).
  4010. *
  4011. * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already
  4012. * exists.
  4013. * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a
  4014. * copy-on-write reflink. If the platform does not support copy-on-write, then a
  4015. * fallback copy mechanism is used.
  4016. * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to
  4017. * create a copy-on-write reflink. If the platform does not support
  4018. * copy-on-write, then the operation will fail.
  4019. *
  4020. * ```js
  4021. * import { copyFile, constants } from 'node:fs';
  4022. *
  4023. * function callback(err) {
  4024. * if (err) throw err;
  4025. * console.log('source.txt was copied to destination.txt');
  4026. * }
  4027. *
  4028. * // destination.txt will be created or overwritten by default.
  4029. * copyFile('source.txt', 'destination.txt', callback);
  4030. *
  4031. * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
  4032. * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
  4033. * ```
  4034. * @since v8.5.0
  4035. * @param src source filename to copy
  4036. * @param dest destination filename of the copy operation
  4037. * @param [mode=0] modifiers for copy operation.
  4038. */
  4039. export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void;
  4040. export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void;
  4041. export namespace copyFile {
  4042. function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise<void>;
  4043. }
  4044. /**
  4045. * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it
  4046. * already exists. Returns `undefined`. Node.js makes no guarantees about the
  4047. * atomicity of the copy operation. If an error occurs after the destination file
  4048. * has been opened for writing, Node.js will attempt to remove the destination.
  4049. *
  4050. * `mode` is an optional integer that specifies the behavior
  4051. * of the copy operation. It is possible to create a mask consisting of the bitwise
  4052. * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`).
  4053. *
  4054. * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already
  4055. * exists.
  4056. * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a
  4057. * copy-on-write reflink. If the platform does not support copy-on-write, then a
  4058. * fallback copy mechanism is used.
  4059. * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to
  4060. * create a copy-on-write reflink. If the platform does not support
  4061. * copy-on-write, then the operation will fail.
  4062. *
  4063. * ```js
  4064. * import { copyFileSync, constants } from 'node:fs';
  4065. *
  4066. * // destination.txt will be created or overwritten by default.
  4067. * copyFileSync('source.txt', 'destination.txt');
  4068. * console.log('source.txt was copied to destination.txt');
  4069. *
  4070. * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
  4071. * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
  4072. * ```
  4073. * @since v8.5.0
  4074. * @param src source filename to copy
  4075. * @param dest destination filename of the copy operation
  4076. * @param [mode=0] modifiers for copy operation.
  4077. */
  4078. export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void;
  4079. /**
  4080. * Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`.
  4081. *
  4082. * `position` is the offset from the beginning of the file where this data
  4083. * should be written. If `typeof position !== 'number'`, the data will be written
  4084. * at the current position.
  4085. *
  4086. * The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`.
  4087. *
  4088. * If this method is `util.promisify()` ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties.
  4089. *
  4090. * It is unsafe to use `fs.writev()` multiple times on the same file without
  4091. * waiting for the callback. For this scenario, use {@link createWriteStream}.
  4092. *
  4093. * On Linux, positional writes don't work when the file is opened in append mode.
  4094. * The kernel ignores the position argument and always appends the data to
  4095. * the end of the file.
  4096. * @since v12.9.0
  4097. * @param [position='null']
  4098. */
  4099. export function writev(
  4100. fd: number,
  4101. buffers: readonly NodeJS.ArrayBufferView[],
  4102. cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void,
  4103. ): void;
  4104. export function writev(
  4105. fd: number,
  4106. buffers: readonly NodeJS.ArrayBufferView[],
  4107. position: number | null,
  4108. cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void,
  4109. ): void;
  4110. export interface WriteVResult {
  4111. bytesWritten: number;
  4112. buffers: NodeJS.ArrayBufferView[];
  4113. }
  4114. export namespace writev {
  4115. function __promisify__(
  4116. fd: number,
  4117. buffers: readonly NodeJS.ArrayBufferView[],
  4118. position?: number,
  4119. ): Promise<WriteVResult>;
  4120. }
  4121. /**
  4122. * For detailed information, see the documentation of the asynchronous version of
  4123. * this API: {@link writev}.
  4124. * @since v12.9.0
  4125. * @param [position='null']
  4126. * @return The number of bytes written.
  4127. */
  4128. export function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number;
  4129. /**
  4130. * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s
  4131. * using `readv()`.
  4132. *
  4133. * `position` is the offset from the beginning of the file from where data
  4134. * should be read. If `typeof position !== 'number'`, the data will be read
  4135. * from the current position.
  4136. *
  4137. * The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file.
  4138. *
  4139. * If this method is invoked as its `util.promisify()` ed version, it returns
  4140. * a promise for an `Object` with `bytesRead` and `buffers` properties.
  4141. * @since v13.13.0, v12.17.0
  4142. * @param [position='null']
  4143. */
  4144. export function readv(
  4145. fd: number,
  4146. buffers: readonly NodeJS.ArrayBufferView[],
  4147. cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void,
  4148. ): void;
  4149. export function readv(
  4150. fd: number,
  4151. buffers: readonly NodeJS.ArrayBufferView[],
  4152. position: number | null,
  4153. cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void,
  4154. ): void;
  4155. export interface ReadVResult {
  4156. bytesRead: number;
  4157. buffers: NodeJS.ArrayBufferView[];
  4158. }
  4159. export namespace readv {
  4160. function __promisify__(
  4161. fd: number,
  4162. buffers: readonly NodeJS.ArrayBufferView[],
  4163. position?: number,
  4164. ): Promise<ReadVResult>;
  4165. }
  4166. /**
  4167. * For detailed information, see the documentation of the asynchronous version of
  4168. * this API: {@link readv}.
  4169. * @since v13.13.0, v12.17.0
  4170. * @param [position='null']
  4171. * @return The number of bytes read.
  4172. */
  4173. export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number;
  4174. export interface OpenAsBlobOptions {
  4175. /**
  4176. * An optional mime type for the blob.
  4177. *
  4178. * @default 'undefined'
  4179. */
  4180. type?: string | undefined;
  4181. }
  4182. /**
  4183. * Returns a `Blob` whose data is backed by the given file.
  4184. *
  4185. * The file must not be modified after the `Blob` is created. Any modifications
  4186. * will cause reading the `Blob` data to fail with a `DOMException` error.
  4187. * Synchronous stat operations on the file when the `Blob` is created, and before
  4188. * each read in order to detect whether the file data has been modified on disk.
  4189. *
  4190. * ```js
  4191. * import { openAsBlob } from 'node:fs';
  4192. *
  4193. * const blob = await openAsBlob('the.file.txt');
  4194. * const ab = await blob.arrayBuffer();
  4195. * blob.stream();
  4196. * ```
  4197. * @since v19.8.0
  4198. * @experimental
  4199. */
  4200. export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise<Blob>;
  4201. export interface OpenDirOptions {
  4202. /**
  4203. * @default 'utf8'
  4204. */
  4205. encoding?: BufferEncoding | undefined;
  4206. /**
  4207. * Number of directory entries that are buffered
  4208. * internally when reading from the directory. Higher values lead to better
  4209. * performance but higher memory usage.
  4210. * @default 32
  4211. */
  4212. bufferSize?: number | undefined;
  4213. /**
  4214. * @default false
  4215. */
  4216. recursive?: boolean;
  4217. }
  4218. /**
  4219. * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html).
  4220. *
  4221. * Creates an `fs.Dir`, which contains all further functions for reading from
  4222. * and cleaning up the directory.
  4223. *
  4224. * The `encoding` option sets the encoding for the `path` while opening the
  4225. * directory and subsequent read operations.
  4226. * @since v12.12.0
  4227. */
  4228. export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir;
  4229. /**
  4230. * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for
  4231. * more details.
  4232. *
  4233. * Creates an `fs.Dir`, which contains all further functions for reading from
  4234. * and cleaning up the directory.
  4235. *
  4236. * The `encoding` option sets the encoding for the `path` while opening the
  4237. * directory and subsequent read operations.
  4238. * @since v12.12.0
  4239. */
  4240. export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void;
  4241. export function opendir(
  4242. path: PathLike,
  4243. options: OpenDirOptions,
  4244. cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void,
  4245. ): void;
  4246. export namespace opendir {
  4247. function __promisify__(path: PathLike, options?: OpenDirOptions): Promise<Dir>;
  4248. }
  4249. export interface BigIntStats extends StatsBase<bigint> {
  4250. atimeNs: bigint;
  4251. mtimeNs: bigint;
  4252. ctimeNs: bigint;
  4253. birthtimeNs: bigint;
  4254. }
  4255. export interface BigIntOptions {
  4256. bigint: true;
  4257. }
  4258. export interface StatOptions {
  4259. bigint?: boolean | undefined;
  4260. }
  4261. export interface StatSyncOptions extends StatOptions {
  4262. throwIfNoEntry?: boolean | undefined;
  4263. }
  4264. interface CopyOptionsBase {
  4265. /**
  4266. * Dereference symlinks
  4267. * @default false
  4268. */
  4269. dereference?: boolean;
  4270. /**
  4271. * When `force` is `false`, and the destination
  4272. * exists, throw an error.
  4273. * @default false
  4274. */
  4275. errorOnExist?: boolean;
  4276. /**
  4277. * Overwrite existing file or directory. _The copy
  4278. * operation will ignore errors if you set this to false and the destination
  4279. * exists. Use the `errorOnExist` option to change this behavior.
  4280. * @default true
  4281. */
  4282. force?: boolean;
  4283. /**
  4284. * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()}
  4285. */
  4286. mode?: number;
  4287. /**
  4288. * When `true` timestamps from `src` will
  4289. * be preserved.
  4290. * @default false
  4291. */
  4292. preserveTimestamps?: boolean;
  4293. /**
  4294. * Copy directories recursively.
  4295. * @default false
  4296. */
  4297. recursive?: boolean;
  4298. /**
  4299. * When true, path resolution for symlinks will be skipped
  4300. * @default false
  4301. */
  4302. verbatimSymlinks?: boolean;
  4303. }
  4304. export interface CopyOptions extends CopyOptionsBase {
  4305. /**
  4306. * Function to filter copied files/directories. Return
  4307. * `true` to copy the item, `false` to ignore it.
  4308. */
  4309. filter?(source: string, destination: string): boolean | Promise<boolean>;
  4310. }
  4311. export interface CopySyncOptions extends CopyOptionsBase {
  4312. /**
  4313. * Function to filter copied files/directories. Return
  4314. * `true` to copy the item, `false` to ignore it.
  4315. */
  4316. filter?(source: string, destination: string): boolean;
  4317. }
  4318. /**
  4319. * Asynchronously copies the entire directory structure from `src` to `dest`,
  4320. * including subdirectories and files.
  4321. *
  4322. * When copying a directory to another directory, globs are not supported and
  4323. * behavior is similar to `cp dir1/ dir2/`.
  4324. * @since v16.7.0
  4325. * @experimental
  4326. * @param src source path to copy.
  4327. * @param dest destination path to copy to.
  4328. */
  4329. export function cp(
  4330. source: string | URL,
  4331. destination: string | URL,
  4332. callback: (err: NodeJS.ErrnoException | null) => void,
  4333. ): void;
  4334. export function cp(
  4335. source: string | URL,
  4336. destination: string | URL,
  4337. opts: CopyOptions,
  4338. callback: (err: NodeJS.ErrnoException | null) => void,
  4339. ): void;
  4340. /**
  4341. * Synchronously copies the entire directory structure from `src` to `dest`,
  4342. * including subdirectories and files.
  4343. *
  4344. * When copying a directory to another directory, globs are not supported and
  4345. * behavior is similar to `cp dir1/ dir2/`.
  4346. * @since v16.7.0
  4347. * @experimental
  4348. * @param src source path to copy.
  4349. * @param dest destination path to copy to.
  4350. */
  4351. export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void;
  4352. interface _GlobOptions<T extends Dirent | string> {
  4353. /**
  4354. * Current working directory.
  4355. * @default process.cwd()
  4356. */
  4357. cwd?: string | undefined;
  4358. /**
  4359. * `true` if the glob should return paths as `Dirent`s, `false` otherwise.
  4360. * @default false
  4361. * @since v22.2.0
  4362. */
  4363. withFileTypes?: boolean | undefined;
  4364. /**
  4365. * Function to filter out files/directories or a
  4366. * list of glob patterns to be excluded. If a function is provided, return
  4367. * `true` to exclude the item, `false` to include it.
  4368. * @default undefined
  4369. */
  4370. exclude?: ((fileName: T) => boolean) | readonly string[] | undefined;
  4371. }
  4372. export interface GlobOptions extends _GlobOptions<Dirent | string> {}
  4373. export interface GlobOptionsWithFileTypes extends _GlobOptions<Dirent> {
  4374. withFileTypes: true;
  4375. }
  4376. export interface GlobOptionsWithoutFileTypes extends _GlobOptions<string> {
  4377. withFileTypes?: false | undefined;
  4378. }
  4379. /**
  4380. * Retrieves the files matching the specified pattern.
  4381. */
  4382. export function glob(
  4383. pattern: string | string[],
  4384. callback: (err: NodeJS.ErrnoException | null, matches: string[]) => void,
  4385. ): void;
  4386. export function glob(
  4387. pattern: string | string[],
  4388. options: GlobOptionsWithFileTypes,
  4389. callback: (
  4390. err: NodeJS.ErrnoException | null,
  4391. matches: Dirent[],
  4392. ) => void,
  4393. ): void;
  4394. export function glob(
  4395. pattern: string | string[],
  4396. options: GlobOptionsWithoutFileTypes,
  4397. callback: (
  4398. err: NodeJS.ErrnoException | null,
  4399. matches: string[],
  4400. ) => void,
  4401. ): void;
  4402. export function glob(
  4403. pattern: string | string[],
  4404. options: GlobOptions,
  4405. callback: (
  4406. err: NodeJS.ErrnoException | null,
  4407. matches: Dirent[] | string[],
  4408. ) => void,
  4409. ): void;
  4410. /**
  4411. * Retrieves the files matching the specified pattern.
  4412. */
  4413. export function globSync(pattern: string | string[]): string[];
  4414. export function globSync(
  4415. pattern: string | string[],
  4416. options: GlobOptionsWithFileTypes,
  4417. ): Dirent[];
  4418. export function globSync(
  4419. pattern: string | string[],
  4420. options: GlobOptionsWithoutFileTypes,
  4421. ): string[];
  4422. export function globSync(
  4423. pattern: string | string[],
  4424. options: GlobOptions,
  4425. ): Dirent[] | string[];
  4426. }
  4427. declare module "node:fs" {
  4428. export * from "fs";
  4429. }